Can a regular expression match whitespace or the start of a string?
I\'m trying to replace currency the abbreviation GBP with a £ symbol. I
A left-hand whitespace boundary - a position in the string that is either a string start or right after a whitespace character - can be expressed with
(?
See a regex demo. Python 3 demo:
import re
rx = r'(? £ 5 Off when you spend £75.00
Note you may use \1 instead of \g<1> in the replacement pattern since there is no need in an unambiguous backreference when it is not followed with a digit.
BONUS: A right-hand whitespace boundary can be expressed with the following patterns:
(?!\S) # A negative lookahead requiring no non-whitespace char immediately to the right of the current position
(?=\s|$) # A positive lookahead requiring a whitespace or end of string immediately to the right of the current position
(?:\s|$) # A non-capturing group matching either a whitespace or end of string
(\s|$) # A capturing group matching either a whitespace or end of string