Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python and "re"

Tags:

python

regex

A tutorial I have on Regex in python explains how to use the re module in python, I wanted to grab the URL out of an A tag so knowing Regex I wrote the correct expression and tested it in my regex testing app of choice and ensured it worked. When placed into python it failed.

After much head scratching I found out the issue, it automatically expects your pattern to be at the start of the string. I have found a fix but I would like to know how to change:

regex = ".*(a_regex_of_pure_awesomeness)"

into

regex = "a_regex_of_pure_awesomeness"

Okay, it's a standard URL regex but I wanted to avoid any potential confusion about what I wanted to get rid of and possibly pretend to be funny.

like image 267
Teifion Avatar asked Sep 16 '08 13:09

Teifion


People also ask

What is the re function in Python?

A regular expression (or RE) specifies a set of strings that matches it; the functions in this module let you check if a particular string matches a given regular expression (or if a given regular expression matches a particular string, which comes down to the same thing).

Does re come with Python?

Python has a built-in package called re , which can be used to work with Regular Expressions.

What is import re in Python?

Regular expression or RegEx in Python is denoted as RE (REs, regexes or regex pattern) are imported through re module. Python supports regular expression through libraries. RegEx in Python supports various things like Modifiers, Identifiers, and White space characters.

How do I use the re lookup function in Python?

Python regex re.search() method looks for occurrences of the regex pattern inside the entire target string and returns the corresponding Match Object instance where the match found. The re.search() returns only the first match to the pattern from the target string.


1 Answers

In Python, there's a distinction between "match" and "search"; match only looks for the pattern at the start of the string, and search looks for the pattern starting at any location within the string.

Python regex docs
Matching vs searching

like image 92
zweiterlinde Avatar answered Oct 30 '22 13:10

zweiterlinde