正则表达式:匹配开始或空格 [英] Regular expression: match start or whitespace

查看:66
本文介绍了正则表达式:匹配开始或空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

<预><代码>>>>进口重新>>>text = u'GBP 5 Off 消费 GBP75.00'>>>re.sub(ur'GBP([\W\d])', ur'£\g<1>', text) # 匹配任意前缀的英镑u'\xa3 5 当您花费 \xa375.00' 时关闭>>>re.sub(ur'^GBP([\W\d])', ur'£\g<1>', text) # 仅在开始时匹配u'\xa3 5 消费 GBP75.00'>>>re.sub(ur'(\W)GBP([\W\d])', ur'\g<1>£\g<2>', text) # 只匹配空格前缀u'GBP 5 Off 消费 \xa375.00'

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

解决方案

使用 OR "|" 运算符:

<预><代码>>>>re.sub(r'(^|\W)GBP([\W\d])', u'\g<1>£\g<2>', text)u'\xa3 5 当您花费 \xa375.00' 时关闭

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 could just match anything starting GBP, but I'd like to be a bit more conservative, and look for certain delimiters around it.

>>> 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'

Can I do both of the latter examples at the same time?

解决方案

Use the OR "|" operator:

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

这篇关于正则表达式:匹配开始或空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆