Using regular expressions in Python

Posted in Uncategorized

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

To use regular expressions in Python, import the “re” module and use Python raw string for the regular expression pattern. For example, if you want to find all non-overlapping three-digit sequences in a string, you can use the findall method …

The findall method returns a list. In the event that it does not find anything, it will return empty list.

The search method finds the first match anywhere in the string. It returns a matchObject if found, and returns None if not found.

To see what methods are in the matchObject, you can …

print(help(matchObject))

The group() method will give you the string found. start() and end() will give you the index of the start and end of that found expression.

The match method works similarly, except it matches the regular expression starting at the start of the string. So the following will return None…

matchObject = re.match(r"\d{3}", "Please call 123-456-7890")

But the following will result in a successful find…

matchObject = re.match(r"\d{3}", "123-456-7890 is where to call")

Regular expressions with compile

If you are using a regular expression pattern often, you can compile it re.compile() and pass it a regular expression and an optional flag (for example, re.IGNORECASE)…

It returns a returns regular expression pattern which you can call methods like “match” on, which then returns a regular match object as before.


Related Posts

Tags

Share This