Python正则表达式返回true / false

问题:Python正则表达式返回true / false

使用Python正则表达式如何获得True/ False返回?所有Python回报是:

<_sre.SRE_Match object at ...>

Using Python regular expressions how can you get a True/False returned? All Python returns is:

<_sre.SRE_Match object at ...>

回答 0

Match对象始终为true,None如果不匹配,则返回。只是测试真实性。

if re.match(...):

Match objects are always true, and None is returned if there is no match. Just test for trueness.

if re.match(...):

回答 1

如果您确实需要TrueFalse,请使用bool

>>> bool(re.search("hi", "abcdefghijkl"))
True
>>> bool(re.search("hi", "abcdefgijkl"))
False

正如其他答案所指出的那样,如果您只是将其用作ifor 的条件while,则可以直接使用它而无需将其包装bool()

If you really need True or False, just use bool

>>> bool(re.search("hi", "abcdefghijkl"))
True
>>> bool(re.search("hi", "abcdefgijkl"))
False

As other answers have pointed out, if you are just using it as a condition for an if or while, you can use it directly without wrapping in bool()


回答 2

伊格纳西奥·巴斯克斯(Ignacio Vazquez-Abrams)是正确的。但要详细说明,re.match()将返回None,其结果为False,或者返回一个匹配对象,该对象将始终True如他所说。仅当您需要有关与正则表达式匹配的部分的信息时,才需要签出匹配对象的内容。

Ignacio Vazquez-Abrams is correct. But to elaborate, re.match() will return either None, which evaluates to False, or a match object, which will always be True as he said. Only if you want information about the part(s) that matched your regular expression do you need to check out the contents of the match object.


回答 3

一种方法是仅针对返回值进行测试。因为您得到<_sre.SRE_Match object at ...>它意味着它将评估为true。当正则表达式不匹配时,您将返回无值,其结果为false。

import re

if re.search("c", "abcdef"):
    print "hi"

产生hi为输出。

One way to do this is just to test against the return value. Because you’re getting <_sre.SRE_Match object at ...> it means that this will evaluate to true. When the regular expression isn’t matched you’ll the return value None, which evaluates to false.

import re

if re.search("c", "abcdef"):
    print "hi"

Produces hi as output.


回答 4

这是我的方法:

import re
# Compile
p = re.compile(r'hi')
# Match and print
print bool(p.match("abcdefghijkl"))

Here is my method:

import re
# Compile
p = re.compile(r'hi')
# Match and print
print bool(p.match("abcdefghijkl"))

回答 5

您可以使用re.match()re.search()。Python提供了两种基于正则表达式的原始操作:re.match()仅在字符串的开头re.search()检查匹配项,而在字符串中的任意位置检查匹配项(这是Perl的默认设置)。参考这个

You can use re.match() or re.search(). Python offers two different primitive operations based on regular expressions: re.match() checks for a match only at the beginning of the string, while re.search() checks for a match anywhere in the string (this is what Perl does by default). refer this