Левая граница пробела - позиция в строке, которая является либо началом строки, либо сразу после символа пробела - может быть выражена с помощью
(?<!\S) # A negative lookbehind requiring no non-whitespace char immediately to the left of the current position
(?<=\s|^) # A positive lookbehind requiring a whitespace or start of string immediately to the left of the current position
(?:\s|^) # A non-capturing group matching either a whitespace or start of string
(\s|^) # A capturing group matching either a whitespace or start of string
См. Демоверсию regex . Демонстрация Python 3 :
import re
rx = r'(?<!\S)GBP([\W\d])'
text = 'GBP 5 Off when you spend GBP75.00'
print( re.sub(rx, r'£\1', text) )
# => £ 5 Off when you spend £75.00
Обратите внимание, что вы можете использовать \1
вместо \g<1>
в шаблоне замены, поскольку нет необходимости в однозначной обратной ссылке, если за ней не следует цифра.
БОНУС: Правая граница пробела может быть выражена с помощью следующих шаблонов:
(?!\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