Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace chars but exclude the word which is using it regex

Tags:

regex

I'm working on a problem where for example there is a sentence: "Today _asf was a null_word day__and __bla__bla". What I would like to get is a sentence where all: _ are replaced with space except in the null_word. So the output sentence should look like this: "Today asf was a null_word day and bla bla ".

To achieve that I wrote a redux expression:

 (\w*((?!null_word)\b\S+)[_]+\w*)

This expression selects all the words that are using _ char and excludes null_word. But now, how do I select all the _ chars from these groups?

I've tried separating them with the following:

 (\w*((?!null_word)\b\S+)[_]+\w*)[_]

but the exampled result is: day__

Thank you for your help!

like image 502
poppytop Avatar asked Jan 19 '26 04:01

poppytop


1 Answers

You could use a negative lookbehind to assert what is directly on the left is not null

(?<!\bnull)_+
  • (?<! Negative lookbehind, assert what is directly on the left is not
    • \bnull Match a wordboundary followed by null
  • ) Close lookbehind
  • _+ Match 1+ times an undersocre

Regex demo

In the replacement use a space.

If you want to keep exactly null_word you might also match that in a capturing group to keep it, and match an underscore to remove it.

Then in the replacement use capturing group 1.

(\bnull_word\b)|_+

Regex demo | Python demo

like image 135
The fourth bird Avatar answered Jan 21 '26 20:01

The fourth bird



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!