Add a custom exception to the regex expression

Viewed 60

This question is related to my previous question, for which I got an answer.

Now I need to add an exception condition into the recommended regex expression. The regex expression (?<!\s)-\s+ should be applied only if the word after - is not equal to to. If it is equal to - to, then the - should be replaced with a single white space .

I tried to use a negative lookbehind (?<!to) to add the condition on to.

import re

s = "refer- ences har- ness Stand- ard Re- quired www.mypo- rtal.test.com A - it is a document, move- to store"
re.sub(r"(?<!\s)-\s+(?<!to)", "", s)

But it still returns moveto store instead of move to store.

The expected output:

references harness Standard Required www.myportal.test.com A - it is a document, move to store
1 Answers

You can use

import re
s = "refer- ences har- ness Stand- ard Re- quired www.mypo- rtal.test.com A - it is a document, move- to store"
print(re.sub(r"(?<!\s)-(?:(\s)+(to)\b|\s+)", r"\1\2", s))
# => references harness Standard Required www.myportal.test.com A - it is a document, move to store

See the Python demo and the regex demo.

Details

  • (?<!\s) - a location with no whitespace immediately on the left
  • - - a hyphen
  • (?:(\s)+(to)\b|\s+) - a non-capturing group matching either of the two patterns:
    • (\s)+(to)\b - a whitespace captured into Group 1 (the group value is referred to with the \1 placeholder, called a replacement backreference, from the replacement pattern), repeated one or more times (so that only the last one lands in the Group 1 memory buffer) and then a whole word to (since \b is a word boundary) that is captured into Group 2 (\2 in the replacement pattern)
    • | - or
    • \s+ - 1+ whitespaces.

The replacement is a concatenation of Group 1 and Group 2. When the first alternative in the non-capturing group does not match, the \1 and \2 are empty strings, so the result is as expected in both cases.

Related