Many Python Regular Expressions need to be matched with substrings, not only during replacement, but also in many places. Next we will learn in detail how to use a Python regular expression to obtain the desired matching substring.
Get the part of a string matched by the regex)
- Regex = ur "..." # Regular Expression
- Match = re. search (regex, subject)
- If match:
- Result = match. group ()
- Else:
- Result = ""
Get the part of a string matched by a capturing group)
- Regex = ur "..." # Regular Expression
- Match = re. search (regex, subject)
- If match:
- Result = match. group (1)
- Else:
- Result = ""
Get the part of a string matched by a named group)
- Regex = ur "..." # Regular Expression
- Match = re. search (regex, subject)
- If match:
- Result = match. group ("groupname ")
- Else:
- Result = ""
Put all matched substrings in the string into the array (Get an array of all regex matches in a string)
- reresult = re.findall(regex, subject)
Traverse all matched substrings (Iterate over all matches in a string)
- for match in re.finditer(r"<(.*?)\s*.*?/\1>", subject)
- # match start: match.start()
- # match end (exclusive): match.end()
- # matched text: match.group()
Create a regular expression object (Create an object to use the same regex for each operations)
- rereobj = re.compile(regex)
Python Regular Expression object version of use regex object for if/else branch whether (part of) a string can be matched)
- rereobj = re.compile(regex)
- if reobj.search(subject):
- do_something()
- else:
- do_anotherthing()
Python Regular Expression object version 2 use regex object for if/else branch whether a string can be matched entirely)
- Rereobj = re. compile (r "\ Z") # End with \ Z at the end of the regular expression
- If reobj. match (subject ):
- Do_something ()
- Else:
- Do_anotherthing ()
The above is an introduction to the application of Python Regular Expressions in obtaining matched substrings.