正则表达式:匹配开始或空格

Mat*_*Mat 50 python regex

正则表达式是否可以匹配空格字符串的开头?

我正在尝试用£符号替换货币缩写GBP.我可以匹配任何以英镑开头的东西,但我想要保守一点,并寻找周围的某些分隔符.

>>> import re
>>> text = u'GBP 5 Off when you spend GBP75.00'

>>> re.sub(ur'GBP([\W\d])', ur'£\g<1>', text) # matches GBP with any prefix
u'\xa3 5 Off when you spend \xa375.00'

>>> re.sub(ur'^GBP([\W\d])', ur'£\g<1>', text) # matches at start only
u'\xa3 5 Off when you spend GBP75.00'

>>> re.sub(ur'(\W)GBP([\W\d])', ur'\g<1>£\g<2>', text) # matches whitespace prefix only
u'GBP 5 Off when you spend \xa375.00'
Run Code Online (Sandbox Code Playgroud)

我可以同时做两个后面的例子吗?

Zac*_*ena 55

使用OR" |"运算符:

>>> re.sub(r'(^|\W)GBP([\W\d])', u'\g<1>£\g<2>', text)
u'\xa3 5 Off when you spend \xa375.00'
Run Code Online (Sandbox Code Playgroud)


Mot*_*tti 36

\b是单词边界,可以是空格,行的开头或非字母数字符号(\bGBP\b).

  • 凉.我从你的答案中学到了两件事.我以前从未在正则表达式中使用过单词边界.2.如果你不小心在Python正则表达式上使用了u'而不是r''前缀,那么事情(尤其是\ b)就不能正常工作. (2认同)
  • 仅供参考,在postgres中,单词边界指示符是\ y而不是\ b (2认同)

Wik*_*żew 12

左侧空白边界 - 字符串中的位置,可以是字符串开头,也可以是空白字符之后的位置 - 可以用以下方式表示

\n\n
(?<!\\S)   # A negative lookbehind requiring no non-whitespace char immediately to the left of the current position\n(?<=\\s|^) # A positive lookbehind requiring a whitespace or start of string immediately to the left of the current position\n(?:\\s|^)  # A non-capturing group matching either a whitespace or start of string \n(\\s|^)    # A capturing group matching either a whitespace or start of string\n
Run Code Online (Sandbox Code Playgroud)\n\n

请参阅正则表达式演示Python 3 演示

\n\n
import re\nrx = r\'(?<!\\S)GBP([\\W\\d])\'\ntext = \'GBP 5 Off when you spend GBP75.00\'\nprint( re.sub(rx, r\'\xc2\xa3\\1\', text) )\n# => \xc2\xa3 5 Off when you spend \xc2\xa375.00\n
Run Code Online (Sandbox Code Playgroud)\n\n

请注意,您可以在替换模式中使用\\1代替\\g<1>,因为当后面没有数字时,不需要明确的反向引用。

\n\n

奖励:右侧空白边界可以用以下模式表示:

\n\n
(?!\\S)   # A negative lookahead requiring no non-whitespace char immediately to the right of the current position\n(?=\\s|$) # A positive lookahead requiring a whitespace or end of string immediately to the right of the current position\n(?:\\s|$)  # A non-capturing group matching either a whitespace or end of string \n(\\s|$)    # A capturing group matching either a whitespace or end of string\n
Run Code Online (Sandbox Code Playgroud)\n


Mar*_*man 6

如果它前面是字符串或字边界的开头(字符串的开头已经是),并且在GBP出现数值或字边界之后,则替换GBP :

re.sub(u'\bGBP(?=\b|\d)', u'£', text)
Run Code Online (Sandbox Code Playgroud)

通过使用前瞻,这消除了对任何不必要的反向引用的需要.足够包容?