Regular Expressions (Python)

Source: Internet
Author: User
Tags locale

Regular Expressions

Regular expressions are a very powerful tool for matching strings, and in other programming languages there is also the concept of regular expressions. In essence, a regular expression (or RE) is a small, highly specialized programming language (in Python) that is embedded in Python and implemented through the RE module. The regular expression pattern is compiled into a sequence of bytecode, which is then executed by a matching engine written in C.

#导入 re module import re s = ' Nick Jenny Nice ' # match way (i) b = Re.match (R ' Nick ', s) q = B.group () print (q) # match Way (b) # Generate Pattern object instance, R table The matching source string a = Re.compile (R ' Nick ') print (type (a))               #<class ' _sre. Sre_pattern ' > b = A.match (s) print (b)                     #<_sre. Sre_match object; Span= (0, 4), match= ' Nick ' > q = B.group () print (q)  #被匹配的字符串放在string中print (b.string)              #nick Jenny nice# The string to match is placed in Re in print (b.re)                  #re. Compile (' Nick ')

The difference between the two matching methods is that the first shorthand is to make a matching formula when each match is compiled, the second way is to match the format in advance (to parse the matching formula), so that the match will not be compiled in the matching format.

Matching rules:

.
"." matches any character (except \ n)
\
"\" Escape character
[...]
"[...]" match character set

# "." matches any character (except \ n) A = Re.match (r ".", "95nick") b = A.group () print (b) Output: 9 # [...] match character Set a = Re.match (r "[A-za-z0-9]", "123Nic K ") B = A.group () print (b) Output: 1

  

  

\d
Match any decimal number; it is equivalent to class [0-9]
Matches any non-numeric character; it is equivalent to a class [^0-9]
\s
Match any whitespace character; it is equivalent to class [\t\n\r\f\v]
\s
Matches any non-whitespace character; it is equivalent to class [^\t\n\r\f\v]
\w
Match any alphanumeric character; it is equivalent to a class [a-za-z0-9]
\w
Matches any non-alphanumeric character; it is equivalent to a class [^a-za-z0-9]

# \d \d Match number/non-digital a = Re.match (r "\d", "Nick") B = A.group () print (b) output: N # \s \s match white/non-whitespace character a = Re.match (r "\s", "") B = A.group () print (b) Output: # \w \w match word character [a-za-z0-9]/non-word character a = Re.match (r "\w", "123Nick") b = A.group () print (b) output: 1a = Re.match (r "\w "," +-*/") b = A.group () print (b) Output: +

  

*
"*" matches the previous character 0 or unlimited times
+
"+" matches a previous character 1 or unlimited times
?
"?" matches a character 0 or 1 times

{m} {M,n}

{m} {M,n} matches the previous character m times or M to n times

*? +? ??

*? +? ?? Match pattern becomes non-greedy (match string as little as possible)
# "*" matches the previous character 0 times or infinite times a = Re.match (r "[a-z][a-z]*", "Aaaaaa123")    #可以只匹配A, 123 does not match on B = A.group () print (b) output: AAAAAAA # " + "match the previous character 1 or infinite times a = Re.match (r" [_a-za-z]+ "," Nick ") B = A.group () print (b) output: Nick #"? "Match a character 0 or 1 times a = Re.match (r" [0-8]?[ 0-9] "(   0-8) no match on 9b = A.group () print (b) Output: 9 # {m} {M,n} matches the previous character m times or M to n times a = Re.match (r" [\w]{6,10} @qq. com "," [email protected] ") B = A.group () print (b) output: [email protected] # *? +? ?? The matching pattern becomes non-greedy (with as few matching strings as possible) A = Re.match (r "[0-9][a-z]*?", "9nick") b = A.group () print (b) output: 9a = Re.match (r "[0-9][a-z]+?", " 9nick ") b = A.group () print (b) Output: 9n

  

 ^ 
 "^" matches the beginning of the string, matching the beginning of each line in multiline mode 
 $ 
 "$" matches the end of the string, matching the end of each line in multiline mode 
 \a 
  
 \a only matches the beginning of the string 
 \z

\z matches only the end of the string

 \b

\b Match a word boundary, which means the position between the word and the space
# "^" matches the beginning of the string, matching the beginning of each line in multiline mode. Li = "Nick\nnjenny\nsuo" a = Re.search ("^s.*", Li,re. M) b = A.group () print (b) output: Suo # "$" matches the end of the string, matching the end of each line in multiline mode. Li = "Nick\njenny\nnick" a = Re.search (". *y$", Li,re. M) b = A.group () print (b) output: Jenny # \a only matches the string at the beginning of li = "Nickjennyk" a = Re.findall (r "\anick", Li) print (a) output: [' Nick '] # \z match only End of String li = "Nickjennyk" a = Re.findall (r "nick\z", Li) print (a) output: [] # \b Matches a word boundary, which means the position between the word and the space a = Re.search (r "\bnick\b", "Jenny Nick Car") B = A.group () print (b) Output: Nick

  

  

 | 
 ' | ' matches either expression 
 ab 
 (AB) expressions in parentheses as a group 
 \<number> 
 \<number> Reference to a string that is numbered num. 
 (? P<key>vlaue) 
 (? P<key>vlaue) match to a dictionary, go to Vlaue can also do alias 
 (? P=name) 
 (? P=name) refers to a grouping match string with alias name 
# "|" matches either expression A = Re.match (r "Nick|jenny", "Jenny") B = A.group () print (b) output: Jenny # (AB) the expression in parentheses as a group A = Re.match (r "[\w ]{6,10}@ (qq|163). com "," [email protected] ") B = A.group () print (b) output: [email protected] # \<number> The group that references num is matched to the string a = Re.match (R "< ([\w]+>) [\w]+</\1", "<book>nick</book>") b = A.group () print (b ) Output: <book>nick</book> # (? p<key>vlace) match output dictionary li = ' Nick Jenny Nnnk ' A = Re.match (? P<k1>n) (? p<k2>\w+). * (? p<k3>n\w+) ", Li) print (a.groupdict ()) output result: {' K2 ': ' ick ', ' K1 ': ' n ', ' K3 ': ' NK '} # (? p<name>) group up an alias # (? P=name) refers to a group matching string with alias name = Re.match (R < (? p<jenny>[\w]+>) [\w]+</(? P=jenny) "," <book>nick</book> "B = A.group () print (b) Output: <book>nick</book>

  

Module Method Introduction:

Match

Match from scratch

Search

Matches the entire string until a match is found


FindAll

Find a match, return the list of all matching parts

Finditer

Returns an iterator

Sub

Replace the part of a string that matches a regular expression with another value

Split

Returns a list of split strings, based on the matching split string

######## Module Method Description ########## match from scratch # search matches the entire string until a match # FindAll found matches, returns a list of all matching parts # findall parentheses li = ' Nick Jenny Ni CK car Girl ' r = Re.findall (' n\w+ ', Li) print (R) #输出结果: [' Nick ', ' Nny ', ' nick ']r = Re.findall (' (n\w+) ', Li) print (R) #输出结果: [' Nick ', ' Nny ', ' nick ']r = Re.findall (' N (\w+) ', Li) print (R) #输出结果: [' ick ', ' NY ', ' ick ']r = Re.findall (' (n) (\w+) (k) ', Li) Print (R) #输出结果: [(' N ', ' ic ', ' K '), (' N ', ' ic ', ' k ')]r = Re.findall (' (n) ((\w+) (c)) (k) ', Li) print (R) #输出结果: [(' N ', ' ic ', ' I ', '  C ', ' K '), (' N ', ' ic ', ' I ', ' C ', ' K ')] # Finditer Returns an iterator, like findall li = ' Nick Jenny Nnnk ' A = Re.finditer (R ' n\w+ ', Li) for I In A:print (I.group ()) # Sub replaces the part of a string that matches a regular expression with a different value Li = ' This is a ' a = Re.sub (r "\d+", "+", Li) print (a) Li = "Nick Njen  NY ncar ngirl "a = Re.compile (r" \bn ") b = a.sub (' cool ', li,3) #后边参数替换几次print (b) #输出结果: #coolick cooljenny coolcar Ngirl # Split returns a list of split strings based on the matching split string li = ' nick,suo jenny:nice car ' a = Re.split (r ": | |,", LI) #或 |print (a) Li = ' Nick1jenny2car3gi Rl5 ' A = Re.compile (r "\d") b = A.split (li) print (b) #输出结果: #[' Nick ', ' Jenny ', ' car ', ' girl ', '] #注意后边空元素 

  

Group ()
Returns the string that is matched by the RE
Groups ()
Returns a tuple containing all the group strings in a regular expression, from 1 to the included group number
Groupdict ()
Return (? p<key>vlace) Dictionary of definitions
Start ()
Returns the position where the match started
End ()
Returns the position where the match ended
Span ()
Returns a tuple containing the index position of the match (start, end)
Li = ' Nick Jenny Nnnk ' A = Re.match ("n\w+", Li) print (A.group ()) A = Re.match ("(n) (\w+)", Li) print (a.groups ()) A = Re.match (" (? P<k1>n) (? p<k2>\w+). * (? p<k3>n\w+) ", Li) print (a.groupdict ()) Output: Nick (' n ', ' ick ') {' K1 ': ' n ', ' K3 ': ' nk ', ' K2 ': ' Ick '}------------------ -----------------------------Import rea = "123abc456" Re.search ("([0-9]*) ([a-z]*] ([0-9]*)", a). Group (0)   # 123abc456, returns the whole Re.search ("([0-9]*) ([a-z]*] ([0-9]*)", a). Group (1)   #123 re.search ("([0-9]*) ([a-z]*] ([0-9]*)", a) . Group (2)   #abc re.search ("([0-9]*) ([a-z]*] ([0-9]*)", a). Group (3)   #456  Group (1) lists the first bracket matching section, Group (2) Lists the second bracket matching section, and Group (3) lists the third Bracket matching section.

  

  

 re. I 
 makes the match case insensitive 
 re. L 
 do localization recognition (locale-aware) match 
 re. M 
 multiline match, affects ^ and $ 
 re. S 
 makes. Matches all characters including line breaks 
 re. U 
 resolves characters based on the Unicode character set.
  This symbol affects \w, \w, \b, \b. 
 re. X 
 
 comment that will affect the space (invalid) 
#re. I   make the match to case insensitive a = Re.search (r "Nick", "Nick", re.) I) Print (A.group ()) #re. L   do localization identification (Locale-aware) to match #re. U   resolves characters based on the Unicode character set. This symbol affects \w, \w, \b, \b. #re. S:. Will match the newline character, default. Commas do not match the newline character a = Re.findall (r ".", "Nick\njenny", re.) S) print (a) output: [' n ', ' I ', ' C ', ' k ', ' \ n ', ' j ', ' e ', ' n ', ' n ', ' y '] #re. The m:^$ flag will match each row, and the default ^ will only match the first line that matches the regular, and the default $ will only match the last row that matches the regular line n = "" "Drummers drumming,11 Pipers piping, Lords a-leaping" "" P = re.com Pile ("^\d+") P_multi = Re.compile ("^\d+", re. M) Print (Re.findall (p,n)) print (Re.findall (p_multi,n))

  

Common regex:

Match phone Number:

# match Phone number phone_num = ' 13001000000 ' a = Re.compile (r "^1[\d+]{10}") B = A.match (phone_num) print (B.group ())

  

Match IPV4:

# match IP Address IP = ' 192.168.1.1 ' a = Re.compile (((1?[ 0-9]? [0-9]) | (2[0-4][0-9]) | (25[0-5])) \.) {3} ((1? [0-9]? [0-9]) | (2[0-4][0-9]) | (25[0-5])) $ ") b = A.search (IP) print (b)

  

Match email:

# match emailemail = ' [email protected] ' A = Re.compile (r "(. *) {0,26}@ (\w+) {0,20}. ( \w+) {0,8} ") B = a.search (email) print (B.group ())

  

Regular Expressions (Python)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.