My regex works on regex101 but doesn't work in python?
re.match
will want to match the string starting at the beginning. In your case, you just need the matching element, correct? In that case you can use something like re.search
or re.findall
, which will find that match anywhere in the string:
>>> re.search(pattern, " |test|").group(0)
'|test|'
>>> re.findall(pattern, " |test|")
['test']
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).
Document
In order to reproduce code that runs on https://regex101.com/, you have to click on Code Generator
on the left handside. This will show you what their website is using. From there you can play around with flags, or with the function you need from re
.
Note:
- https://regex101.com/ uses
re.MULTILINE
as default flag - https://regex101.com/ uses
re.finditer
as default method
import re
regex = r"where"
test_str = "select * from table where t=3;"
matches = re.finditer(regex, test_str, re.MULTILINE)
for matchNum, match in enumerate(matches, start=1):
print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))
for groupNum in range(0, len(match.groups())):
groupNum = groupNum + 1
print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))