Here, we will explain the basics of regular expressions in Python.
import re
m1 = re.match(r'ab*', 'a') #Repeat 0 or more times of the previous character (b)
if m1:
print(m1.group(0))
else:
print('Not match')
m2 = re.match(r'ab+', 'a') #One or more repetitions of the previous letter (b)
if m2:
print(m2.group(0))
else:
print('Not match')
m3 = re.match(r'ab?', 'abb') #Repeat 0 or 1 of the previous character (b)
if m3:
print(m3.group(0))
else:
print('Not match')
m4 = re.match(r'ab$', 'abb') #Does it match the end of the string?
if m4:
print(m4.group(0))
else:
print('Not match')
m5 = re.match(r'[a-e]', 'f') # []One of the characters in (a, b, c, d,Does it match e)
if m5:
print(m5.group(0))
else:
print('Not match')
import re
#Does it match from the beginning
match = re.match(r'\d+-*\d+$', '012-3456')
print(match.group(0)) # '012-3456'
#Do you match on the way
search = re.search(r'\d{3}', '012-3456')
print(search.group(0)) # '012'
#List all matching patterns
print(re.findall(r'\d{3}', '012-3456')) # ['012', '345']
#Split by the specified pattern delimiter
print(re.split(r'[,、]', '1,2, san')) # ['1', '2', 'Mr.']
#Convert characters of the specified pattern to another pattern
print(re.sub(r'(\d),(\d)', r'\2,\1', '1,2, san')) # 2,1, san
Here, I explained the basics of regular expressions in Python. If you want to match a specific string pattern, it is convenient to use a regular expression.
What is the programming language Python? Can it be used for AI and machine learning?
Recommended Posts