Python 为什么提供的正则表达式返回true?
我想知道为什么以下正则表达式返回true:Python 为什么提供的正则表达式返回true?,python,regex,Python,Regex,我想知道为什么以下正则表达式返回true: reg = re.compile (r'[0-9]%') reg.search ("50%") [0-9]将匹配任何单个数字,在本例中为5。但是0不匹配%,因此它应该返回false,但返回true 我的代码可能有语法错误,但你可以理解它的要点。这个正则表达式将匹配50%的0%部分。这个正则表达式将匹配50%的0%部分。search()匹配字符串中任何位置的模式(因此它匹配0%)。如果希望整个字符串匹配,请尝试以下操作: 重新编译(r'^[0-9]%$
reg = re.compile (r'[0-9]%')
reg.search ("50%")
[0-9]
将匹配任何单个数字,在本例中为5。但是0不匹配%,因此它应该返回false,但返回true
我的代码可能有语法错误,但你可以理解它的要点。这个正则表达式将匹配
50%
的0%
部分。这个正则表达式将匹配50%
的0%
部分。search()匹配字符串中任何位置的模式(因此它匹配0%)。如果希望整个字符串匹配,请尝试以下操作:
重新编译(r'^[0-9]%$)
^-匹配字符串的开头
$-匹配字符串的结尾reg.search()匹配字符串中任何位置的模式(因此它匹配0%)。如果希望整个字符串匹配,请尝试以下操作:
重新编译(r'^[0-9]%$)
^-匹配字符串的开头
$-匹配字符串结尾如果要搜索较长字符串中的一位数百分比,可以使用:
[171]中的
:打印(重新搜索(')(?如果要搜索较长字符串中的一位数百分比,可以使用:
[171]中的:print(re.search)(“(?正如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%
正如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%
如果您不希望正则表达式匹配,例如“5%”(但仍然匹配,例如“15%”),您应该真正使用match
而不是search
如果您不希望正则表达式匹配,例如“5%”(但仍然匹配,例如“15%”),您应该真正使用match
而不是search