Python Regex Returns A Part Of The Match When Used With Re.findall
I have been trying to teach myself Python and am currently on regular expressions. The instructional text I have been using seems to be aimed at teaching Perl or some other languag
Solution 1:
Use a non-capturing group:
result = re.findall( r'\$[0-9]+(?:\.[0-9][0-9])?', inputstring)
^^
The re.findall
function returns the list of captured texts if there are any defined in the pattern, and you have one in yours. You need to get rid of it by turning it into a non-capturing one.
re.findall(pattern, string, flags=0) If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group.
Update
You can shorten your regex a bit by using a limiting quantifier{2}
that requires exactly 2 occurrences of the preceding subpattern:
r'\$[0-9]+(?:\.[0-9]{2})?'
^^^
Or even replace [0-9]
with \d
:
r'\$\d+(?:\.\d{2})?'
Post a Comment for "Python Regex Returns A Part Of The Match When Used With Re.findall"