简体   繁体   English

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

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

I am having issues with matching this particular regex in python, can someone see what is wrong? 我在与python中的特定正则表达式匹配时遇到问题,有人可以看到这是什么问题吗?

Sample strings I am trying to match with a single regular expression are: 我尝试与单个正则表达式匹配的示例字符串是:

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

I have tried the following, but there doesnt seem to be a single expression that matches all of them: 我已经尝试了以下方法,但是似乎没有一个匹配所有条件的表达式:

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

I am trying to catch (5.50, 1.2, 0.5, 0, etc.) 我正在尝试赶上(5.50、1.2、0.5、0等)

You need to make the first .* match non-greedy (add a ? ), it'll swallow the numbers otherwise: 您需要使第一个.*不匹配(添加? ),否则它将吞噬数字:

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

I've also made the optional .number part a non-capturing group to simplify processing the output: 我还将可选的.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',)

I'd suggest using the : as the anchor. 我建议使用:作为锚点。 That way, you get a more robust expression: 这样,您将获得一个更强大的表达式:

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

You might even want to add on the MP suffix if it's guaranteed to be in the text. 如果可以保证在文本中包含MP后缀,您甚至可能希望添加。

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

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