re.match is anchored at the beginning of the string. That has nothing to do with newlines, so it is not the same as using ^ in the pattern.
As the re.match documentation says:
If zero or more characters at the beginning of string match the regular expression pattern, return a corresponding
MatchObjectinstance. ReturnNoneif the string does not match the pattern; note that this is different from a zero-length match.Note: If you want to locate a match anywhere in string, use
search()instead.
re.search searches the entire string, as the documentation says:
Scan through string looking for a location where the regular expression pattern produces a match, and return a corresponding
MatchObjectinstance. ReturnNoneif no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string.
So if you need to match at the beginning of the string, or to match the entire string use match. It is faster. Otherwise use search.
The documentation has a specific section for match vs. search that also covers multiline strings:
Python offers two different primitive operations based on regular expressions:
matchchecks for a match only at the beginning of the string, whilesearchchecks for a match anywhere in the string (this is what Perl does by default).Note that
matchmay differ fromsearcheven when using a regular expression beginning with'^':'^'matches only at the start of the string, or inMULTILINEmode also immediately following a newline. The “match” operation succeeds only if the pattern matches at the start of the string regardless of mode, or at the starting position given by the optionalposargument regardless of whether a newline precedes it.
Now, enough talk. Time to see some example code:
# example code:
string_with_newlines = """something
someotherthing"""
import re
print re.match('some', string_with_newlines) # matches
print re.match('someother',
string_with_newlines) # won't match
print re.match('^someother', string_with_newlines,
re.MULTILINE) # also won't match
print re.search('someother',
string_with_newlines) # finds something
print re.search('^someother', string_with_newlines,
re.MULTILINE) # also finds something
m = re.compile('thing$', re.MULTILINE)
print m.match(string_with_newlines) # no match
print m.match(string_with_newlines, pos=4) # matches
print m.search(string_with_newlines,
re.MULTILINE) # also matches
Answer from nosklo on Stack OverflowHow do I return a string from a regex match in python? - Stack Overflow
python - How can I make a regex match the entire string? - Stack Overflow
How do you use re.match() ? Python
`re.match()`: raise exception if string doesn't match? - Ideas - Discussions on Python.org
re.match is anchored at the beginning of the string. That has nothing to do with newlines, so it is not the same as using ^ in the pattern.
As the re.match documentation says:
If zero or more characters at the beginning of string match the regular expression pattern, return a corresponding
MatchObjectinstance. ReturnNoneif the string does not match the pattern; note that this is different from a zero-length match.Note: If you want to locate a match anywhere in string, use
search()instead.
re.search searches the entire string, as the documentation says:
Scan through string looking for a location where the regular expression pattern produces a match, and return a corresponding
MatchObjectinstance. ReturnNoneif no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string.
So if you need to match at the beginning of the string, or to match the entire string use match. It is faster. Otherwise use search.
The documentation has a specific section for match vs. search that also covers multiline strings:
Python offers two different primitive operations based on regular expressions:
matchchecks for a match only at the beginning of the string, whilesearchchecks for a match anywhere in the string (this is what Perl does by default).Note that
matchmay differ fromsearcheven when using a regular expression beginning with'^':'^'matches only at the start of the string, or inMULTILINEmode also immediately following a newline. The “match” operation succeeds only if the pattern matches at the start of the string regardless of mode, or at the starting position given by the optionalposargument regardless of whether a newline precedes it.
Now, enough talk. Time to see some example code:
# example code:
string_with_newlines = """something
someotherthing"""
import re
print re.match('some', string_with_newlines) # matches
print re.match('someother',
string_with_newlines) # won't match
print re.match('^someother', string_with_newlines,
re.MULTILINE) # also won't match
print re.search('someother',
string_with_newlines) # finds something
print re.search('^someother', string_with_newlines,
re.MULTILINE) # also finds something
m = re.compile('thing$', re.MULTILINE)
print m.match(string_with_newlines) # no match
print m.match(string_with_newlines, pos=4) # matches
print m.search(string_with_newlines,
re.MULTILINE) # also matches
search ⇒ find something anywhere in the string and return a match object.
match ⇒ find something at the beginning of the string and return a match object.
You should use re.MatchObject.group(0). Like
imtag = re.match(r'<img.*?>', line).group(0)
Edit:
You also might be better off doing something like
imgtag = re.match(r'<img.*?>',line)
if imtag:
print("yo it's a {}".format(imgtag.group(0)))
to eliminate all the Nones.
Note that re.match(pattern, string, flags=0) only returns matches at the beginning of the string. If you want to locate a match anywhere in the string, use re.search(pattern, string, flags=0) instead (https://docs.python.org/3/library/re.html). This will scan the string and return the first match object. Then you can extract the matching string with match_object.group(0) as the folks suggested.
Try with specifying the start and end rules in your regex:
re.compile(r'^test-\d+$')
Since Python 3.4 you can use re.fullmatch to avoid adding ^ and $ to your pattern.
>>> import re
>>> p = re.compile(r'\d{3}')
>>> bool(p.match('1234'))
True
>>> bool(p.fullmatch('1234'))
False
I’ve been looking at tutorials and I can’t figure out why I can’t get it to work, I’m trying to see if a substring matches a certain format but the output is incorrect.
re.match(‘[A-Z],[A-Z] $’ , s)
Is this not how to set it up?
Link to the example
So I'm trying to make a regex that matches from opening to closing '<>' brackets. So I've figured out that '(<[^<^>])*(>)*' should work pretty well, so I've tried it in regex101.com, and it worked perfectly (matched <pair<int,string>> in 'List<pair<int,string>>') but when I try it in Python terminal (v3.8 if it matters), it matches only the inside brackets (re.findall returns [('', ''), ('', ''), ('', ''), ('', ''), ('<int,string', '>'), ('', '')]). I've used the same expression, and the same flags (multiline).
Does anyone know what could cause that to be different?
Curious, have you checked out the code generator on regex101?
https://regex101.com/r/FYmNPx/1/codegen?language=python
regex101 only emulates the functionality, not an exact representation of python
I don't think it know the various rules of findall - when you use capture groups, result will depend on the number of capture groups used
In this case I don't think you are interested in capture groups, you only want the overall match. So, use non-capturing groups
>>> s = 'List<pair<int,string>>'
>>> re.findall(r'(?:<[^<>]+)+>+', s)
['<pair<int,string>>']
If capture groups are used, each element of output will be a tuple of strings of all the capture groups. Text matched by the RE outside of capture groups won't be present in the output list. If there is only one capture group, tuple won't be used and each element will be the matched portion of that capture group.
>>> re.findall(r'ab*c', 'abc ac adc abbc xabbbcz bbb bc abbbbbc')
['abc', 'ac', 'abbc', 'abbbc', 'abbbbbc']
>>> re.findall(r'a(b*)c', 'abc ac adc abbc xabbbcz bbb bc abbbbbc')
['b', '', 'bb', 'bbb', 'bbbbb']
>>> re.findall(r'(x*):(y*)', 'xx:yyy x: x:yy :y')
[('xx', 'yyy'), ('x', ''), ('x', 'yy'), ('', 'y')]
If you use regex third party module, you can do it for any number of nesting:
>>> regex.findall(r'<(?:[^<>]++|(?0))++>', 'List<pair<int,string>> <a<b<c<d>>>>')
['<pair<int,string>>', '<a<b<c<d>>>>']
See my book (https://github.com/learnbyexample/py_regular_expressions/blob/master/py_regex.md#recursive-matching) for explanation