Skip to content Skip to sidebar Skip to footer

Update Regex Expression To Consider Multiple Scenarios

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_st

Solution 1:

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.

Solution 2:

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)

Post a Comment for "Update Regex Expression To Consider Multiple Scenarios"