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

时间:2009-02-08 12:38:09

标签: 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'

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

8 个答案:

答案 0 :(得分:48)

使用OR“|”运算符:

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

答案 1 :(得分:32)

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

答案 2 :(得分:6)

如果前面是字符串的开头或者word boundary(字符串的开头已经是),并且在GBP出现数值或字边界之后,这将取代GBP:

re.sub(u'\bGBP(?=\b|\d)', u'£', text)

这样就不需要使用lookahead进行任何不必要的反向引用。足够包容?

答案 3 :(得分:2)

我认为你正在寻找'(^|\W)GBP([\W\d])'

答案 4 :(得分:0)

是的,为什么不呢?

re.sub(u'^\W*GBP...

匹配字符串的开头,0或更多的空格,然后是GBP ...

编辑:哦,我想你想要改变,使用|

re.sub(u'(^|\W)GBP...

答案 5 :(得分:0)

在搜索之前,您始终可以从令牌中修剪前导和尾随空格,如果它不是需要整行的匹配/分组情况。

答案 6 :(得分:0)

它适用于Perl:

$text = 'GBP 5 off when you spend GBP75';
$text =~ s/(\W|^)GBP([\W\d])/$1\$$2/g;
printf "$text\n";

输出结果为:

$ 5 off when you spend $75

请注意,我规定匹配应该是全局的,以便全部出现。

答案 7 :(得分:0)

左侧空格边界-字符串中的位置,可以是字符串开头,也可以是空格字符之后的位置-可以用

表示
(?<!\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 demoPython 3 demo

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