Python learning-regular expressions, python Regular Expressions
A regular expression is a special character sequence that helps you easily check whether a string matches a certain pattern.
The re module enables the Python language to have all the regular expression functions.
The compile function generates a regular expression object based on a mode string and optional flag parameters. This object has a series of methods for regular expression matching and replacement.
The re module also provides functions that are exactly the same as those of these methods. These functions use a pattern string as their first parameter.
1. Regular Expression modifier-optional flag
The regular expression can contain some optional identifier modifiers to control the matching mode.
Modifier is specified as an optional flag. Multiple tags can be specified by bitwise OR (|. For example, re. I | re. M is set to I and M.
| Modifier |
Description |
| Re. I |
Make matching case insensitive |
| Re. L |
Perform locale-aware matching |
| Re. M |
Multi-row matching, affecting ^ and $ |
| Re. S |
Make. Match All characters including line breaks |
| Re. U |
Parses Characters Based on the Unicode Character Set. This flag affects \ w, \ W, \ B, \ B. |
| Re. X |
This flag gives you a more flexible format so that you can write regular expressions more easily. |
2. Regular Expression Mode
List the regular expression metacharacters and syntaxes supported by Python (picture from http://www.cnblogs.com/huxi/archive/2010/07/04/1771073.html)
3. re Module
1) re. match Function
Re. match tries to match a pattern from the starting position of the string. If the match is not successful, match () returns none.
Function Syntax: re. match (pattern, string, flags = 0)
Pattern: matched Regular Expression
String: matched string
Flags: A flag used to control the matching mode of regular expressions, such as case-sensitive or multi-row matching.
The re. match Method returns a matched object. Otherwise, None is returned.
| Start () |
Returns the starting position of the match. |
| End () |
Returns the position at which the match ends. |
| Span () |
Returns the position where a tuple contains a match (START, end ). |
| Group () |
Returns the string matched by the RE. |
| Group (num = 0) |
The string that matches the entire expression. group () can input multiple group numbers at a time. In this case, it returns a tuples that contain the values of those groups. |
| Groups () |
Returns a tuple containing all group strings, from 1 to the group number contained. |
Instance 1:
1 #! /Usr/bin/env python 2 #-*-coding: UTF-8-*-3 ''' 4 # @ time: 5 # @ author: huange 6 # @ version: 1.1 7 # @ file: test2.py 8 # @ Software: PyCharm 9 ''' 10 import re11 print (re. match ('www ', 'www .hh.com '). span () # Match 12 print (re. match ('com ', 'www .hh.com') # do not match the starting position 13 14 15 results: 16 () 17 None
Example 2:
1 #! /Usr/bin/python3 2 import re 3 4 line = "Cats are smarter than dogs" 5 6 obj = re. match (R' (. *) are (.*?) . * ', Line, re. M | re. i) 7 8 if obj: 9 print ("obj. group (): ", obj. group () 10 print ("obj. group (1): ", obj. group (1) 11 print ("obj. group (2): ", obj. group (2) 12 print (obj. start () 13 print (obj. end () 14 print (obj. groups () 15 else: 16 print ("No match !! ") 17 18 19 result: 20 obj. group (): Cats are smarter than dogs21 obj. group (1): Cats22 obj. group (2): smarter23 024 2625 ('cats', 'smarter ')
2) re. search function
Re. search scans the entire string and returns the first successful match.
Function Syntax:Re.Match(Pattern,String,Flags=0)
Pattern: matched Regular Expression
String: matched string
Flags: A flag used to control the matching mode of regular expressions, such as case-sensitive or multi-row matching.
The re. search Method returns a matched object. Otherwise, None is returned.
Instance 1:
1 import re2 print (re. search ('www ', 'www .hh.com '). span () 3 print (re. search ('com ', 'www .hh.com '). span () 4 5 Results: 6 () 7)
Example 2:
1 #! /Usr/bin/python3 2 import re 3 4 line = "Cats are smarter than dogs" 5 6 obj = re. search (R' (. *) are (.*?) . * ', Line, re. M | re. i) 7 8 if obj: 9 print ("obj. group (): ", obj. group () 10 print ("obj. group (1): ", obj. group (1) 11 print ("obj. group (2): ", obj. group (2) 12 print (obj. start () 13 print (obj. end () 14 print (obj. groups () 15 else: 16 print ("No match !! ") 17 18 19 result: 20 obj. group (): Cats are smarter than dogs21 obj. group (1): Cats22 obj. group (2): smarter23 024 2625 ('cats', 'smarter ')
PS: re. match only matches the start of the string. If the start of the string does not match the regular expression, the match fails. The function returns None; re. search matches the entire string until a match is found.
3) re. sub function
Re. sub is used to replace the matching options in the string.
Function Syntax: re. sub (pattern, repl, string, count = 0)
Pattern: The pattern string in the regular expression.
Repl: a replacement string. It can also be a function.
String: the original string to be searched and replaced.
Count: the maximum number of times a pattern is replaced. The default value 0 indicates that all matches are replaced.
Instance 1:
1 #! /Usr/bin/python3 2 import re 3 phone = '2017-135-4238 # phone Number '4 5 # Delete comment 6 num = re. sub ('#. * $ ', '', phone) 7 print (num) 8 9 # Delete non-character 10 num = re. sub ('\ d', '', phone) 11 print (num) 12 13 Results: 14 135-4238-5642 15 13542385642
Example 2:
1 #! /Usr/bin/python 2 3 import re 4 5 # multiply the matched number by 2 6 def double (matched): 7 value = int (matched. group ('value') 8 return str (value * 2) 9 10 s = 'a23g4hfd567' 11 print (re. sub ('(? P <value> \ d +) ', double, s) 12 13. The result is: 14 A46G8HFD1134.
4) re. split Function
Function Syntax: re. split (pattern, string, maxsplit)
Split string by matching substrings and return to the list. Maxsplit is used to specify the maximum number of splits. If not specified, all splits are performed.
1 import re2 3 p = re. split (R' \ d + ', 'one1two2three3four4') 4 print (p)
Result:
['One', 'two', 'three ', 'four', '']
5) re. findall Function
Returns all matched substrings in the form of a list.
Function Syntax: re. findall (pattern, string, flags ):
1 import re2 3 p = re. findall (r '\ d +', 'one1two2three3four4 ') 4 print (p) 5 6 RESULTS: 7 ['1', '2', '3', '4']