Regex For Matching String With Trailing Whitespace Works In Perl But Not Python
I'm trying to find strings that have trailing whitespace, i.e. 'foo ' as opposed to 'foo'. In Perl, I would use: $str = 'foo '; print 'Match\n' if ($str =~ /\s+$/) ; When I try th
Solution 1:
Use re.search()
instead; re.match()
only matches at the start of a string. Quoting the re.match()
documentation:
If zero or more characters at the beginning of string match the regular expression pattern, return a corresponding
MatchObject
instance.
Emphasis mine.
In other words, re.match()
is the equivalent of the m/.../
match operator in Perl, while re.search()
is the same as /.../
.
Solution 2:
Because re.match(r'\s+$', str)
is equivalent to re.search(r'\A\s+$', str)
. Use re.search
instead.
From docs:
re.match()
checks for a match only at the beginning of the string, whilere.search()
checks for a match anywhere in the string (this is what Perl does by default).
Post a Comment for "Regex For Matching String With Trailing Whitespace Works In Perl But Not Python"