Python Regular Expressions require a variety of matching methods, but we cannot blindly match them. Next we will introduce ten matching methods for Python regular expressions that we often encounter. I hope you will gain some benefits.
1. test whether the Python Regular Expression matches all or part of the string.
- Regex = ur "..." # Regular Expression
- If re. search (regex, subject ):
- Do_something ()
- Else:
- Do_anotherthing ()
2. test whether the Python Regular Expression matches the entire string.
- Regex = ur "... \ Z" # The regular expression ends with \ Z.
- If re. match (regex, subject ):
- Do_something ()
- Else:
- Do_anotherthing ()
3. Create a matching object and obtain matching details through the object.
- Regex = ur "..." # Regular Expression
- Match = re. search (regex, subject)
- If match:
- # Match start: match. start ()
- # Match end (exclusive): match. end ()
- # Matched text: match. group ()
- Do_something ()
- Else:
- Do_anotherthing ()
4. Obtain the substring matched by the Python Regular Expression
- Regex = ur "..." # Regular Expression
- Match = re. search (regex, subject)
- If match:
- Result = match. group ()
- Else:
- Result = ""
5. Obtain the substring matching the capture group.
- Regex = ur "..." # Regular Expression
- Match = re. search (regex, subject)
- If match:
- Result = match. group (1)
- Else:
- Result = ""
6. Obtain the substring matched by the famous group
- Regex = ur "..." # Regular Expression
- Match = re. search (regex, subject)
- If match:
- Result = match. group ("groupname ")
- Else:
- Result = ""
7. Put all matched substrings in the string into the array.
- reresult = re.findall(regex, subject)
8. 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()
9. Create a regular expression object using a Python Regular Expression string
- (Create an object to use the same regex for many
operations)
- rereobj = re.compile(regex)
10. Python Regular Expression object version in use 1
- rereobj = re.compile(regex)
- if reobj.search(subject):
- do_something()
- else:
- do_anotherthing()
The above is a solution for matching problems related to Python regular expressions.