regex

Regex with lookbehind searching for substring


I need help with a Regex. I want to replace all occurrences of 5% or 7% or 183% or 99% to `` (empty string) BUT if the occurrence is 0% or 100% (it could be dozens of occurrences that I want to preserve) I dont want to do anything.

For example:

aaa 0% bbb should become aaa 0% bbb (nothing changed)

However

aaa 40% bbb should become aaa bbb

I came up with a regex using negative lookbehind but it just removes the % sign, not the number. This is the regex:

replace (?<!(0|100))% with `` (empty string)

The regex above, when applied to the string aaa 40% bbb returns aaa 40 bbb.


Solution

  • There's nothing bad to use a lookbehind in this situation if you describe correctly what stands before the numbers (a space here).

    \ \d+(?<! 0| 100)%
    

    demo

    (I added a backslash before the first space only to be more readable, obviously you can remove it).

    Simply put the space before the number.

    Note that choosing the lookbehind allows to start the pattern with \ \d+ that avoids quickly uninteresting positions in the string (without to enter in an assertion or a group). Following the same idea, you can also use:

    \ \d+%(?<! 0%| 100%)
    

    if your string contains many numbers not followed with a %