簡體   English   中英

為什么提供的正則表達式返回true?

[英]Why does this provided regular expression return true?

我想知道為什么以下正則表達式返回true:

reg = re.compile (r'[0-9]%')
reg.search ("50%")

[0-9]將匹配任何單個數字,在這種情況下為5。但是0不匹配%,因此它應返回false,但返回true。

我的代碼可能有語法錯誤,但是您可以理解。

reg.search()會在字符串中的任何位置匹配模式(因此它匹配0%)。 如果您希望整個字符串都匹配,請嘗試以下操作:

re.compile(r'^ [0-9]%$')

^-匹配字符串的開頭

$-匹配字符串的結尾

此正則表達式將匹配50%0%部分。

如果要在較長的字符串中搜索個位數百分比,則可以在后面使用負數

In [171]: print(re.search('(?<!\d)\d%',"Foo is 5% complete"))
<_sre.SRE_Match object at 0xab302f8>

In [172]: print(re.search('(?<!\d)\d%',"Foo is 50% complete"))
None

In [173]: print(re.search('(?<!\d)\d%',"5% complete"))
<_sre.SRE_Match object at 0xab301a8>

In [174]: print(re.search('(?<!\d)\d%',"50% complete"))
None

正如gfdunn2所提到的,它對整個字符串進行“滾動匹配”。 您可以做一些事情來控制它更好一些。

下面的花括號{}可以控制您獲得多少個字符,因此它將使您的匹配更加緊密。

>>> import re  

#exactly 1 digit and %
>>> test = re.compile(r'[0-9]{1}%')  
>>> print test.search("50%").group(0)  
0%  


#exactly 2 digits and %
>>> test = re.compile(r'[0-9]{2}%')  
>>> print test.search("50%").group(0)  
50%  


#one or more digits  
>>> test = re.compile(r'[0-9]+%')  
>>> print test.search("50%").group(0)  
50%  

#in the event you want to include floating point percentages  
>>> test = re.compile(r'[0-9.]+%')  
>>> print test.search("50.4%").group(0)  
50.4%

>>> print test.search("50.34%").group(0)
50.34%

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM