当前位置:网站首页>Regular replacement [JS, regular expression]

Regular replacement [JS, regular expression]

2022-07-04 20:04:00 qq_ twenty-two million eight hundred and forty-one thousand thr

Problem description

Representation number _ Niuke Tiba _ Cattle from (nowcoder.com)
The title requires that all figures be replaced with * Numbers *

Originally, I intended to use this question routinely c++ To write , But in the process of writing, I suddenly realized
Replace all numbers , Don't you just find all the numbers and replace them ? Then you can use Regular expressions

With this idea , I'll find the corresponding regular expression

Solve the code

var value = readline();

console.log(value.replace(/(\d+)/g, (number) => {
    
    return `*${
      number}*`;
} ))

you 're right , Just two sentences …… I was also a little shocked when I submitted the answer successfully ……
 Please add a picture description

The course of thinking

In fact, when I first got this topic , I already knew that it can be replaced by regularization , But it's just a little short , Let me solve this problem
How to not just replace , Instead, add characters and replace
So I found that it can be used Function to replace

1. Get all the numbers

The first step is to get all the numbers through regular expressions ,/(\d+)/g

  • (\d+): Match one or more numbers
  • /g: The global matching , And replaceAll similar

In fact, I know how to replace numbers /[0-9]/g, It can also match all the numbers , But it is not the result we want .
adopt /[0-9]/g Look for numbers , Only one number can be found , Because only one number is satisfied 0-9 On this condition
And by (\d+) Then you can Match to consecutive numbers

2. Replace assignment

After finding all the numbers , The second step is how to replace the number with * Numbers * 了 .
Directly through the function to deal with

(number) => {
    
    return `*${
      number}*`;
}

Because the first step , We have found all the consecutive numbers , Then we can connect these figures , After processing , And back out

  • number: All the numbers
  • With * Numbers * returns
原网站

版权声明
本文为[qq_ twenty-two million eight hundred and forty-one thousand thr]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/185/202207041715557935.html