1. Re.match function
Re.match tries to match a pattern from the beginning of the string, if it is not successful at the starting position. Match () will return none
Syntax: Re.match (pattern,string,flags=0)
Pattern: Regular expression to match
String: Target string
Flags: Used to control how expressions are matched, such as: case sensitivity, multiline matching, and so on.
Print (Re.match ('www','www.ruboob.com'3)# match at start position Print (Re.match ('com','www.ruboo.com') None # does not match at start position
2. Group () function to get the matching expression
>>> line = " cats is smarter than dogs " >>> p = re.match (R" (. *). * " >>> P <_sre. Sre_match object; span= (0, Match=
cats is smarter than dogs
" >>>>
P.group ()
"
cats is smarter than dogs
" >>> P.group (1
cats "
3. Re.search function
Re.search scans the entire string and returns the first successful match.
Syntax: Re.search (pattern,string,flags)
4, the difference between re.search&re.match
Re.match matches only the beginning of the string, if the string does not begin to conform to the regular expression, the match fails and the function returns none;
Re.search matches the entire string until a match is found.
5. Search and replace
Python's re module provides a match for re.sub to replace a string
Syntax: Re.sub (pattern,repl,string,count=0,flags=0)
A special mark for marking special information.
Parameters:
Pattern: Patterns string in regular
REPL: The replacement string, or as a function
String: The strings to be looked up
Count: The maximum number of times a pattern match is replaced, and the default of 0 means that all matches are replaced
>>> phone ='2004-959-559 # This is a foreign phone number'>>> num = re.sub (r'#.+',"', phone)#Remove Chinese comments>>>Num'2004-959-559'>>> num = re.sub (r'\d',"', phone)#Remove the small horizontal bar>>>Num'2004959559'
REPL is a function
import re # Multiply the matched number by 2 def double (matched): value = Int (Matched.group ( " value " ) return str (value * 2) s = " a23g4hfd567 print (re.sub ( ' (? p<value>\d+) " , double, s)) Span style= "COLOR: #008000" ># result a46g8hfd1134
Regular expressions in Python