Skip navigation.

Regex "Match" in Python vs. C#

Regex "Match" in Python vs. C#

I have been writing a lot of code in both C# and Python lately... flipping back and forth between both languages.  One thing I keep getting tripped up on is the terminology used in regular expression syntax, and what a "match" is.

So for my own disambiguation:

  • Python's re.match() is different than C#'s Regex.IsMatch()
  • Python's re.search() is similar to C#'s Regex.IsMatch()


Better explained in code:


Using Regex.IsMatch() in C# to match a pattern with some text:

if (Regex.IsMatch("foobar", "bar"))
{
    Console.WriteLine("Match");
}
else
{
    Console.WriteLine("No Match");
}

this prints 'Match'


Same thing, using re.match() in Python:

if re.match('bar', 'foobar'):
    print 'Match'
else:
    print 'No Match'

this prints 'No Match'


oops.. didn't get a match. What happened?

match() only checks if the regex matches at the beginning of the string, while search() will scan forward through the string for a match.


If you were expecting the pattern to match anywhere in the string, you need to use re.search() instead:

if re.search('bar', 'foobar'):
    print 'Match'
else:
    print 'No Match'

this prints 'Match'


... or else you must supply a pattern that will match from the beginning of the string:

if re.match('.*bar', 'foobar'):
    print 'Match'
else:
    print 'No Match'

this prints 'Match'