Question

for which I have to replace all numbers with a text tag 'NUMBER'. but there is a certain condition it shouldn't be changed, when ever a number exists with an underscore in it .. (e.g 123_456). I am using

s/\d+/NUMBER/g

but it changes the likes of 123_456 to NUMBER_NUMBER. Is there a way to exclude it? The [^xyz] pattern might not work, as it negates a single character at a time (this is my understanding). Any ideas ? Input file sample is: The last number shouldn't be changed.

received for code:3
received for code:1
received for code:9
received for code:33
received for code:4
received for code:323_456
Was it helpful?

Solution

You can use word boundaries to avoid matching digits that are followed by a underscore:

s/\b\d+\b/NUMBER/g

OTHER TIPS

Match only groups of digits that don't have a _ before or after:

s/(?<![_0-9])[0-9]+(?![_0-9])/NUMBER/g;

Note that \d isn't usually what people want, since it can match many more characters that are characterized as digits than just 0-9. (Though the /a flag does make it mean just 0-9.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top