簡體   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