python regular two

 

In python, we can use the re module to use regular expressions.

Regular expressions use \ to escape special characters, because python itself also uses \ as escape, so when using regular expressions, there will be two slashes in 'python\\.org', in order to avoid In this case, we can use the following methods:

r'python\.org'

 

Some common methods of the re module.

findall

Returns all matching strings as a list, or an empty list if no matches are found.

You can also specify the start and end positions of the string.

import re
string = "abcd2135asdfasfd3425"
re = re.compile(r'\d+')
result1 = re.findall(string)
result2 = re.findall(string,0,8) #Specify   the starting position, from the first character to the eighth character, so the last number will not match 
print (result1)
 print (result2)

result:
['2135', '3425']
['2135']

 

search

Return as long as a match is found, and you can also specify a starting position.

import re
string = "abcd2135asdfasfd3425"
re = re.compile(r'\d+')
result1 = re.search(string)
result2 = re.search(string,0,6)   #Specify the starting position, match the numbers from the 1st character to the 6th character 
print (result1.group())
 print (result2.group())

result:
2135
21

 

match

If no starting position is specified, the default matches the head of the string. Returns None if there is no match.

import re
string = "abcd2135asdfasfd3425"
re = re.compile(r'\d+')
result1 = re.match(string)
result2 = re.match(string,2,6) #Start matching from c, and because match is the default matching string header, and the header is c is not a number result3 = re.match 
(string,4,6) #From 2 start matching 
print (result1)
 print (result2)
 print (result3.group())

result:
None
None
21

 

Online regular expression matching website: https://regex101.com/ We can debug regular expressions here.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325279775&siteId=291194637