繁体   English   中英

python中的此正则表达式匹配有什么问题?

[英]What is wrong with this regex match in python?

我在与python中的特定正则表达式匹配时遇到问题,有人可以看到这是什么问题吗?

我尝试与单个正则表达式匹配的示例字符串是:

string = '[Pre-Avatar Mode Cost: 5.50 MP]'
string = '[Pre-Avatar Mode Cost: 1.2 MP]'
string = '[Pre-Avatar Mode Cost: 0.5 MP]'
string = '[Post-Avatar Mode: 0 MP]'

我已经尝试了以下方法,但是似乎没有一个匹配所有条件的表达式:

m = re.match('\[.*(?P<cost>\d+(\.\d+)).*\]', string) # Appears to match only ones with #.#
m = re.match('\[.*(?P<cost>\d+(\.\d+)?).*\]', string) # Appears to match the 0 only, unable to print out m.groups for the others

我正在尝试赶上(5.50、1.2、0.5、0等)

您需要使第一个.*不匹配(添加? ),否则它将吞噬数字:

r'\[.*?(?P<cost>\d+(?:\.\d+)?).*\]'

我还将可选的.number部分设置为一个非捕获组,以简化对输出的处理:

>>> import re
>>> costre = re.compile(r'\[.*?(?P<cost>\d+(?:\.\d+)?).*\]')
>>> costre.match('[Post-Avatar Mode: 0 MP]').groups()
('0',)
>>> costre.match('[Post-Avatar Mode: 5.50 MP]').groups()
('5.50',)
>>> costre.match('[Post-Avatar Mode: 1.2 MP]').groups()
('1.2',)

我建议使用:作为锚点。 这样,您将获得一个更强大的表达式:

r'\[.*: (?P<cost>\d+(?:\.\d+)?).*\]'

如果可以保证在文本中包含MP后缀,您甚至可能希望添加。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM