The methods used in the RE module are:
1, compile ()
Compiling a regular expression pattern is an object pattern, which can improve execution efficiency.
Grammar:
Re.compile (R ' pattern ', [flags])
where R means not escaping the string, which means \ t is .
For example:
Import Rehello = "hello,i am tom,nice to konw U." A = Re.compile (R ' to ') b = a.findall (hello) ["to", ' to ']
2. Match ()
The matching string must begin with pattern, otherwise it will not match.
Grammar:
Re.match (Pattern,string,[flags])
For example:
>>> a = "Hello" >>> b = Re.match (R ' L ', a) >>> b>>> C = re.match (R ' he ', a) >>> C&L T;_sre. Sre_match object; span= (0, 2), match= ' he ' >
3. Search ()
A match to the first pattern returns the result.
Grammar:
Re.search (Pattern,string,[flags])
For example:
>>> a = "Hellohe" >>> C = re.search (R ' he ', a). Group () >>> C ' he '
Note: The group () method is used to return a string because the search () method returns a Match object.
4, FindAll ()
Matches all of the pattern and returns a list.
Grammar:
Re.findall (Pattern,string,[flags])
For example:
>>> a = "Hello12kk32" >>> B = Re.findall (R ' \d+ ', a) >>> b[' 12 ', ' 32 ']
5, Sub ()
Match and replace.
Grammar:
Re.sub (Pattern,repl,string,count)
Example:
Import Retext = "Jgood is a handsome boy, he's cool, clever, and so on ..." Print (Re.sub (R ' \s+ ', '-', text)) execution results are as follows: Jgood-is -a-handsome-boy,-he-is-cool,-clever,-and-so-on ... The second parameter is the replaced string; In this case, the '-' fourth parameter refers to the number of replacements. The default is 0, which means that each match is replaced.
Python Module Learning re