3

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 this in Python 2.6, e.g.:

import re

str = 'foo '
if re.match('\s+$', str):
    print 'Match'

it doesn't match. I feel like I'm missing something obvious but I can't figure out what I'm doing wrong.

2
  • Thanks to everyone for the quick responses. I knew it had to be something pretty simple. Commented Jan 14, 2014 at 17:52
  • You should also notice that the answers use a raw string for the regex as well, i.e. r'\s+$' where 'r' is before the quotes. This prevents python from treating escaped characters as special. Commented Jan 14, 2014 at 18:02

2 Answers 2

2

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 /.../.

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, while re.search() checks for a match anywhere in the string (this is what Perl does by default).

1
  • 3
    Not quite; it is equivalent to re.search('\A\s+$', str), a subtle difference. Commented Jan 14, 2014 at 17:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.