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.
Re.match (Pattern, String, flags=0) # match successfully returns a matching object, otherwise none returned
1 Import Re2 Print (Re.match (' www ', ' www.runoob.com '). span ()) # matches at the starting position (0, 3) 3 print (Re.match (' com ', ' Www.runoob.com ') # does not match at start position None
1 Import re 2 line = "Cats is smarter than dogs" 3 Matchobj = Re.match (R ' (. *) is (. *?). * ', line, re. M|re. I) 4 # matchobj = Re.match (R ' (. *) is (. *). * ', line, re. M|re. I) # Same as the result 5 6 if Matchobj:7 print ("Matchobj.group ()", Matchobj.group ()) # cats is smarter than dogs 8
print ("Matchobj.group (1)", Matchobj.group (1)) # cats 9 Print ("Matchobj.group (2)", Matchobj.group (2)) # smarter10 else:11 print ("No match!!")
1 Import re 2 line = "Cats is smarter than dogs" 3 Matchobj = Re.match (R ' (. *) are (. *?) (. *). * ', line, re. M|re. I) 4 # matchobj = Re.match (R ' (. *) is (. *) (. *). * ', line, re. M|re. I) #这个结果也一样 5 6 if Matchobj:7 print ("Matchobj.group ()", Matchobj.group ()) # cats is smarter than Dogs 8 Print ("Matchobj.group (1)", Matchobj.group (1)) # cats 9 Print ("Matchobj.group (2)", Matchobj.group (2)) # smarter10 Print ("Matchobj.group (3)", Matchobj.group (3)) # than11 else:12 print ("No match!!")
Use the group (NUM) or groups () Match object function to get a match expression.
Groups (): Returns a tuple containing all the group strings, from 1 to the included group number.
Re.search scans the entire string and returns the first successful match.
Print (Re.search (' www ', ' www.runoob.com '). span ()) # matches at the starting position (0, 3) print (Re.search (' com ', ' www.runoob.com ' ). span ()) # does not match starting position (11, 14)
1 Import Re2 line = "Cats is smarter than dogs"; 3 Searchobj = Re.search (R ' (. *) is (. *?). * ', line, re. M | Re. I) 4 if Searchobj:5 print ("Searchobj.group ():", Searchobj.group ()) # Cats is smarter than Dogs 6 Print ("Searchobj.group (1):", Searchobj.group (1)) # Cats7 Print ("Searchobj.group (2):", Searchobj.group (2)) # Smarter8 else:9 print ("Nothing found!!")
1 line = "Cats is smarter than dogs" 2 matchobj = Re.match (R ' Dogs ', line, re.) M | Re. I) 3 if Matchobj:4 print ("match-to-Matchobj.group ():", Matchobj.group ()) 5 else:6 print ("No match!!") 7 8 matchobj = Re.search (R ' Dogs ', line, re. M | Re. I) 9 If matchobj:10 print ("Search-and Matchobj.group ():", Matchobj.group ()) Else:12 print ("No match!!") "No match!!" Search--Matchobj.group (): dogs16 "
Re.match matches only the beginning of the string, if the string does not begin to conform to the regular expression, the match fails, the function returns none, and Re.search matches the entire string until a match is found.
1 Re.search (pattern, String, flags=0) 2 re.sub (Pattern, Repl, String, count=0, flags=0)
The RE module provides re.sub to replace matches in a string.
Parameters:
Pattern: The modal string in the regular.
REPL: The replacement string, or a function .
String: The original string to be looked up for replacement.
Count: The maximum number of times a pattern match is replaced, and the default of 0 means that all matches are replaced.
1 phone = "2004-959-559 # foreign phone number" 2 # delete the Python comment in the string 3 num = re.sub (R ' #.*$ ', "", phone) 4 print ("Phone number is:", num) # The phone number is: 2004-959-559 5 6 # Delete a non-numeric (-) string 7 num = re.sub (R ' \d ', "", phone) 8 print ("Phone number is:", num) # number is: 2004959559
The REPL parameter is a function
1 # Multiply the matching numbers by the number Def double (matched): 3 value = Int (Matched.group (' value ')) 4 return str (value * 2) 5 6 s = ' a23g4hfd56 7 ' 7 print (Re.sub (? p<value>\d+) ', double, s)
| Re. I |
Make the match case insensitive |
| Re. L |
Do localization identification (locale-aware) matching |
| Re. M |
Multiline match, affecting ^ and $ |
| Re. S |
Make. Match all characters, including line breaks |
| Re. U |
Resolves characters based on the Unicode character set. This sign affects \w, \w, \b, \b. |
| Re. X |
This flag is given by giving you a more flexible format so that you can write regular expressions much easier to understand. |
Re. I | Re. M... Multiple flags can be specified by a bitwise OR (|).
Regular expression pattern
A pattern string uses a special syntax to represent a regular expression: letters and numbers denote themselves.
| ^ |
Matches the beginning of a string |
| $ |
Matches the end of the string. |
| . |
Matches any character, except the newline character, when re. When the Dotall tag is specified, it can match any character that includes a line feed. |
| [...] |
Used to represent a set of characters, listed separately: [AMK] matches ' a ', ' m ' or ' K ' |
| [^...] |
Characters not in []: [^ABC] matches characters other than a,b,c. |
| re* |
Matches 0 or more expressions. |
| Re+ |
Matches 1 or more expressions. |
| Re? |
Matches 0 or 1 fragments defined by a preceding regular expression, not greedy |
| re{N} |
|
| re{N,} |
Exact match n preceding expression. |
| re{N, m} |
Matches N to M times the fragment defined by the preceding regular expression, greedy way |
| a| B |
Match A or B |
| (RE) |
The G matches the expression in parentheses, and also represents a group |
| (? imx) |
The regular expression consists of three optional flags: I, M, or X. Affects only the areas in parentheses. |
| (?-imx) |
The regular expression closes I, M, or x optional flag. Affects only the areas in parentheses. |
| (?: RE) |
A similar (...), but does not represent a group |
| (? imx:re) |
Use I, M, or x optional flag in parentheses |
| (?-imx:re) |
I, M, or x optional flags are not used in parentheses |
| (?#...) |
Comments. |
| (? = re) |
Forward positive qualifiers. If a regular expression is included, ... Indicates that a successful match at the current position succeeds or fails. But once the contained expression has been tried, the matching engine is not improved at all, and the remainder of the pattern attempts to the right of the delimiter. |
| (?! Re) |
Forward negative qualifier. As opposed to a positive qualifier, when the containing expression cannot match the current position of the string |
| (?> re) |
Match the standalone mode, eliminating backtracking. |
| \w |
Match alphanumeric and underline |
| \w |
Match non-alphanumeric and underline |
| \s |
Matches any whitespace character, equivalent to [\t\n\r\f]. |
| \s |
Match any non-null character |
| \d |
Match any number, equivalent to [0-9]. |
| \d |
Match any non-numeric |
| \a |
Match string start |
| \z |
Matches the end of the string, if there is a newline, matches only the ending string before the line break. C |
| \z |
Match string End |
| \g |
Matches the position where the last match was completed. |
| \b |
Matches a word boundary, which is the position between a word and a space. For example, ' er\b ' can match ' er ' in ' never ', but not ' er ' in ' verb '. |
| \b |
Matches a non-word boundary. ' er\b ' can match ' er ' in ' verb ', but cannot match ' er ' in ' Never '. |
| \ n, \ t, et. |
Matches a line break. Matches a tab character. such as |
| \1...\9 |
Matches the contents of the nth grouping. |
| \10 |
Matches the contents of the nth grouping, if it is matched. Otherwise, it refers to an expression of octal character code. |
Instance
1. Character Matching
Python matches "Python".
2. Character classes
| [Pp]ython |
Match "python" or "python" |
| Rub[ye] |
Match "Ruby" or "Rube" |
| [Aeiou] |
Match any one of the letters within the brackets |
| [0-9] |
Match any number. Similar to [0123456789] |
| [A-z] |
Match any lowercase letter |
| [A-z] |
Match any uppercase letter |
| [A-za-z0-9] |
Match any letters and numbers |
| [^aeiou] |
All characters except the Aeiou letter |
| [^0-9] |
Matches characters except for numbers |
3. Special character classes
| . |
Matches any single character except "\ n". To match any character including ' \ n ', use a pattern like ' [. \ n] '. |
| \d |
Matches a numeric character. equivalent to [0-9]. |
| \d |
Matches a non-numeric character. equivalent to [^0-9]. |
| \s |
Matches any whitespace character, including spaces, tabs, page breaks, and so on. equivalent to [\f\n\r\t\v]. |
| \s |
Matches any non-whitespace character. equivalent to [^ \f\n\r\t\v]. |
| \w |
Matches any word character that includes an underscore. Equivalent to ' [a-za-z0-9_] '. |
| \w |
Matches any non-word character. Equivalent to ' [^a-za-z0-9_] '. |
R indicates that the string is a non-escaped raw string, so the compiler ignores the backslash, which ignores the escape character.
(. *) The first matching group, * represents all characters except the newline character.
(.*?) Second Matching group, *? Multiple question marks in the back, representing non-greedy mode, that is, matching only the minimum characters that match the criteria
The last one. * Not surrounded by parentheses, so not grouped, the matching effect is the same as the first one, but does not count towards the matching result.