Python development [module]: re regular, python Development re
Re Module
Preface:
The re module is used to operate python regular expressions.
'. 'By default, any character except \ n is matched. If flag DOTALL is specified, any character is matched, including the line break '^'. If flags MULTILINE is specified, this can also be matched (r "^ a", "\ nabc \ neee", flags = re. MULTILINE) '$' matches the end of a character, or e. search ("foo $", "bfoo \ nsdfsf", flags = re. MULTILINE ). group () can also '*' match the character before * 0 or multiple times, re. findall ("AB *", "cabb3abcbbac") Returns ['abb', 'AB', 'a'] '+' to match the previous character once or multiple times, re. findall ("AB +", "AB + cd + abb + bba") result ['AB', 'abb'] '? 'Match the previous character once or 0 times '{m}' match the previous character m times '{n, m}' match the previous CHARACTER n to m times, re. findall ("AB {1, 3}", "abb abc abbcbbb") results in 'abb', 'AB', 'abb'] '|' match | left or | right character, re. search ("abc | ABC", "ABCBabcCD "). group () Result 'abc ''(...) 'Group match, re. search ("(abc) {2} a (123 | 456) c", "abcabca456c "). the result of group () is abcabca456c' [a-z] ', which matches any one of the characters from a to z' [^ () for the characters in the escape quotation marks of any character other than r'', view the \ character details. 7' \ a' matches only from the beginning of the character, re. search ("\ Aabc", "alexabc") is the end of the unmatched '\ Z' character. It matches the number 0-9' \ d with $ '\ d'. 'Match non-number' \ W' match [A-Za-z0-9] '\ W' match non-[A-Za-z0-9]' \ s' match white space character, \ t, \ n, \ r, re. search ("\ s +", "AB \ tc1 \ n3 "). group () Result '\ t ''(? P <name>...) 'group match re. search ("(? P <province> [0-9] {4 })(? P <city> [0-9] {2 })(? P <birthday> [0-9] {4}) "," 371481199306143242 "). result of groupdict ("city") {'province ': '000000', 'city': '81', 'birthday': '000000'} re. IGNORECASE ignores case-insensitive re. search ('(\ A | \ s) red (\ s + | $)', I, re. IGNORECASE)
The flag is the pattern modifier. If the regular expression is not changed, the meaning of the regular expression is changed using the pattern modifier to adjust matching results:
# FlagsI = IGNORECASE = encoding # case insensitive when ignore case is matched L = LOCALE = encoding # assume current 8-bit locale for local identification and matching U = UNICODE = sre_compile.SRE_FLAG_UNICODE # assume unicode locale according to Unicode character and resolution character M = MULTILINE = sre_compile.SRE_FLAG_MULTILINE # make anchors look for newline multi-line match S = DOTALL = sre_compile.SRE_FLAG_DOTALL # make dot match newline. match includes line breaks, that is, after the pattern is corrected ,". "matching can match any character X = VERBOSE = sre_compile.SRE_FLAG_VERBOSE # ignore whitespace and comments.
Greedy mode and lazy mode:
Import reresult1 = re. search ("p. * y "," abcdfphp435pythony_py ") # Greedy mode print (result1) # <_ sre. SRE_Match object; span = (5, 21), match = 'php435pythony _ py'> result2 = re. search ("p. *? Y "," abcdfphp435pythony_py ") # Lazy mode print (result2) # <_ sre. SRE_Match object; span = (5, 13), match = 'php435py'>
Match:
Match the specified content in the string according to the model starting from the starting position:
# Matchimport re obj = re. match ('\ d +', '123ua123sf ') # match one or more numbers from the first character print (obj) # <_ sre. SRE_Match object; span = (0, 3), match = '000000'> if obj: # if any matching character exists, print (obj. group () # print the matched content #123
Matched IP Address:
import reip = '255.255.255.253'result=re.match(r'^([1-9]?\d|1\d\d|2[0-4]\d|25[0-5])\.([1-9]?\d|1\d\d|2[0-4]\d|25[0-5])\.' r'([1-9]?\d|1\d\d|2[0-4]\d|25[0-5])\.([1-9]?\d|1\d\d|2[0-4]\d|25[0-5])$',ip)print(result)# <_sre.SRE_Match object; span=(0, 15), match='255.255.255.253'>
Search:
Match the specified content in the string based on the model (not necessarily the initial position) and match the first
# Searchimport reobj = re. search ('\ d +', 'a123u234asf') # match one or more numbers in print (obj) # <_ sre. SRE_Match object; span = (1, 4), match = '000000'> if obj: # if any matching character exists, print (obj. group () # print the matched content #123 import reobj = re. search ('\ ([^ ()] + \)', 'sdds (a1fwe2 (3uusfdsf2) 34as) F') # match print (obj) # <_ sre. SRE_Match object; span = (13, 24), match = '(3uusfdsf2)'> if obj: # if any matching character exists, execute. if it is null, print (obj. group () # print the matched content # (3uusfdsf2)
Differences between group and groups:
# Differences between group and groups import rea = "123abc456" B = re. search ("([0-9] *) ([a-z] *) ([0-9] *)", a) print (B) # <_ sre. SRE_Match object; span = (0, 9), match = '123abc456 '> print (B. group () # 123abc456print (B. group (0) # 123abc456print (B. group (1) #123 print (B. group (2) # abcprint (B. group (3) #456 print (B. groups () # ('123', 'abc', '123 ')
Findall:
The preceding two methods are used to match a single value, that is, only one of the strings can be matched. If you want to match all the elements that meet the conditions in the string, use findall; Use findall without group.
# Findallimport reobj = re. findall ('\ d +', 'a123u234asf') # match multiple if obj: # execute if any matching character exists. if it is null, print (obj) is not executed) # The generated content is a list # ['123', '123']
Sub:
Used to replace matched strings (pattern, repl, string, count = 0, flags = 0)
#subimport recontent = "123abc456"new_content = re.sub('\d+', 'ABC', content)print(new_content)#ABCabcABC
Split:
Grouping based on specified matches (pattern, string, maxsplit = 0, flags = 0)
# Splitimport recontent = "1-2*(60-30 + 1*(9-2*5/3 + 7/3*99/4*2998 + 10*568/14 )) -(-4*3)/(16-3*2) "new_content = re. split ('\ *', content) # Use * to split it into print (new_content) # ['1-2', '(60-30 + 1 ', '(9-2', '2014 + 5/3 ', '2014 + 1', '2014 + 10 ', '2014 + 1)-(-4', '3)/(16-3 ', '2) '] content = "'1-2*(60-30 + 1*(9-2*5/3 + 7/3*99/4*2998 + 10*568/14 )) -(-4*3)/(16-3*2) '"new_content = re. split ('[\ + \-\ * \/] +', content) # new _ Content = re. split ('\ *', content, 1) print (new_content) # ["'1", '2', '(60', '30', '1 ', '(9', '2', '5', '3', '7', '3', '99', '4', '123 ', '10', '123', '14) ', #' (', '4', '3)', '(16', '3 ', "2) '"] inpp = '1-2*(60-30 + (-40-5) * (9-2*5/3 + 7/3*99/4*2998 + 10*568/14)-(-4*3)/(16-3*2) 'inpp = re. sub ('\ s *', '', inpp) # Remove the white space character print (inpp) new_content = re. split ('\ ([\ + \-\ * \/]? \ D + [\ + \-\ * \/]? \ D +) {1} \) ', inpp, 1) print (new_content) #['1-2*(60-30 +', '-40-5 ', '* (9-2*5/3 + 7/3*99/4*2998 + 10*568/14)-(-4*3)/(16-3*2)']
Supplement r'' escape:
fdfdsfds\fdssfdsfds& @$
Lzl. py
First of all, it should be clear that the program reads\ CharacterAdded to the listYes \\:
Import re, sysli = [] with open('lzl.txt ', 'R', encoding = "UTF-8") as file: for line in file: li. append (line) print (li) # Note: The single slash in the file will become a double slash after it is read # ['fdfdsfds \ fds \ n ', 'sfdsfds & @ $ '] print (li [0]) # single slash when printing # fdfdsfds \ fds
R characterThe meaningCharacter \ProceedEscape,\ OnlyAsCharacterAppears:
Import re, sysli = [] with open('lzl.txt ', 'R', encoding = "UTF-8") as file: for line in file: print (re. findall (r's \ F', line) # match the first method # print (re. findall ('\\\\', line) # The second method matches li. append (line) print (li) # Note: The single slash in the file, after reading it, it will become a double slash # ['s \ F'] # [] # ['fdfdsfds \ fds \ n', 'sfdsfds & @ $ ']
Supplement: After reading the following code, you may be more confused.
Import rere. findall (R' \ ', line) # print (R' \') can only be written in this way in the Regular Expression and cannot be written as R '\\') # Only writing in this way can not be written as R' \ '\ can only be a double number # \ result # If you want to print a single value \ write as the following print ('\\') # It can only be a double number # \ result
Summary: The single slash \ in the file, the double slash \ when reading the program, and the print is the single slash \. When the regular expression matches the file but the slash, use the dashes '\' to match, or use the dashes '\' instead of r to match.
Compile functions:
Note:
Python supports regular expressions through the re module. The general procedure for using re is to use re first. the compile () function is used to compile the regular expression string form into a Pattern instance. Then, the Pattern instance is used to process text and obtain matching results (a Match instance). Finally, the Match instance is used to obtain information, perform other operations
A simple example is to find all the English characters in a string:
import repattern = re.compile('[a-zA-Z]')result = pattern.findall('as3SiOPdj#@23awe')print(result)# ['a', 's', 'S', 'i', 'O', 'P', 'd', 'j', 'a', 'w', 'e']
Matched IP address (255.255.255.255 ):
import repattern = re.compile(r'^(([1-9]?\d|1\d\d|2[0-4]\d|25[0-5])\.){3}([1-9]?\d|1\d\d|2[0-4]\d|25[0-5])$')result = pattern.match('255.255.255.255')print(result)# <_sre.SRE_Match object; span=(0, 15), match='255.255.255.255'>