Regular Expressions
A regular expression is a special sequence of characters that can help you easily check whether a string matches a pattern.
Python has added the RE module since version 1.5, which provides a Perl-style regular expression pattern.
The RE module enables the Python language to have all the regular expression functionality.
The compile function generates a regular expression object based on a pattern string and an optional flag parameter. The object has a series of methods for regular expression matching and substitution.
The RE module also provides functions that are fully consistent with these methods, which use a pattern string as their first parameter.
This section focuses on the regular expression handlers commonly used in Python.
Re.match function
Re.match attempts to match a pattern from the starting position of the string, and if the match is not successful, match () returns none.
function Syntax :
string, flags=0)
| Parameters |
Description |
| Pattern |
Matched regular Expressions |
| String |
The string to match. |
| Flags |
A flag bit that controls how regular expressions are matched, such as case sensitivity, multiline matching, and so on. |
The match succeeds Re.match method returns a matching object, otherwise none is returned.
We can use the group (NUM) or groups () matching object function to get a matching expression.
| Matching Object Methods |
Description |
| Group (num=0) |
A string that matches the entire expression, group () can enter more than one group number at a time, in which case it returns a tuple that contains the corresponding values for those groups. |
| Groups () |
Returns a tuple containing all the group strings, from 1 to the included group number. |
1 #-*-coding:utf-8-*-2 3 ImportRe4 Print(Re.match ('www','www.runoob.com'). span ())#match at start position5 Print(Re.match ('com','www.runoob.com'))#Do not match at start position
Results:
1 (0, 3)2 None
1 ImportRe2 3line ="Cats is smarter than dogs"4 5Matchobj = Re.match (r'(. *) is (. *?). *', line, re. m|Re. I)6 7 ifMatchobj:8 Print "Matchobj.group ():", Matchobj.group ()9 Print "Matchobj.group (1):", Matchobj.group (1)Ten Print "Matchobj.group (2):", Matchobj.group (2) One Else: A Print "No match!!"
Results:
1 Matchobj.group (): Cats is smarter than dogs2 matchobj.group (1): Cats3 matchobj.group (2): Smarter
[Python Study Notes] Regular expressions