Python regex matches only the whole string

Is there an easy way to check if a regular expression matches an entire string in Python? I thought putting $in the end would do it, but it turns out that it $doesn't work if new lines are completed.

For example, the following returns a match, even if this is not what I want.

re.match(r'\w+$', 'foo\n')
+4
source share
4 answers

You can use \Z:

\Z

Matches only at the end of a line.

In [5]: re.match(r'\w+\Z', 'foo\n')

In [6]: re.match(r'\w+\Z', 'foo')
Out[6]: <_sre.SRE_Match object; span=(0, 3), match='foo'>
+4
source

You can use a negative lookahead statement to require that it is $not followed by a trailing newline:

>>> re.match(r'\w+$(?!\n)', 'foo\n')
>>> re.match(r'\w+$(?!\n)', 'foo')
<_sre.SRE_Match object; span=(0, 3), match='foo'>

re.MULTILINE ; OP , . , $ :

[ re.MULTILINE], '^' ( ); '$' ( ). '^' '$' ( ) .

, re.X.

+2

, , :

m = re.match(r".*", mystring)
start, stop = m.span()
if stop-start == len(mystring):
    print("The entire string matched")

. ( ) , .

+2

Based on @alexis answer: a full compliance check method might look like this:

def fullMatch(matchObject, fullString):
    if matchObject is None:
        return False
    start, stop = matchObject.span()
    return stop-start == len(fullString):

Where fullStringis the string to which you are applying the regular expression, and matchObjectis the resultmatchObject = re.match(yourRegex, fullString)

0
source

Source: https://habr.com/ru/post/1621021/


All Articles