Update regex expression to consider multiple scenarios

Viewed 41

I need to replace - in test_string:

import re
test_string = "refer- ences har- ness Stand- ard Re- quired www.mypo- rtal.test.com This - is a document"
re.sub(r"[- ]", "", test_string)

The expected result:

references harness Standard Required www.myportal.test.com This - is a document

Basically, the replacement should happen only when there is no white space before -.

How can I do so? Currently I get this:

referencesharnessStandardRequiredwww.myportal.test.comThisisadocument

I appreciate of someone could also explain the solution (not just give a correct regex expression)

2 Answers

You can use

import re
test_string = "refer- ences har- ness Stand- ard Re- quired www.mypo- rtal.test.com This - is a document"
print(re.sub(r"(?<!\s)-\s+|", "", test_string))
# => references harness Standard Required www.myportal.test.com This - is a document

See the regex demo and the Python demo.

Details

  • (?<!\s) - a negative lookbehind that fails the match if there is a whitespace immediately to the left of the current location
  • - - a hyphen
  • \s+ - one or more whitespace chars.
import re
test_string = "refer- ences har- ness Stand- ard Re- quired www.mypo- rtal.test.com This - is a document"
test_string = re.sub(r'[a-zA-Z0-9]- ', '', test_string)
print(test_string)
Related