可以用简单的方式解释Python正则表达式语法吗
你将在这篇博客中学习正则表达式(RegEx)并使用Python的re模块与RegEx进行交互(通过示例的帮助)。
正则表达式(RegEx)是一系列定义搜索模式的字符。例如,
^a…s$是一个定义的RegEx模式。任何以a和s结尾的五个字母字符串都形成这个模式。
Python使用名为re的模块来处理RegEx。下面是一个示例:
import re
pattern = '^a...s$'
test_string = 'abyss'
result = re.match(pattern, test_string)
if result:
print("Search successful.")
else:
print("Search unsuccessful.")
不同类型的语法用于这些操作
re.findall()
re.findall()方法返回一个包含所有匹配项的字符串列表。
示例
从字符串中提取数字的程序。
import re
string = 'hello 12 hi 89. Howdy 34'
pattern = '\d+'
print("Entered String=",string)
result = re.findall(pattern, string)
print("The numbers in the above string",result)
输出
Entered String= hello 12 hi 89. Howdy 34
The numbers in the above string ['12', '89', '34']
如果找不到匹配的模式,re.findall()将返回一个空列表。
re.search()
re.search()方法接受两个参数:一个模式和一个字符串。该方法在字符串中寻找第一个与正则表达式模式匹配的位置。
如果搜索成功,re.search()将返回一个匹配对象;如果失败,则返回None。
字符串
match = re.search(pattern, str)
示例
import re
string = "Python is fun"
#check if 'Python' is at the beginning
match = re.search('\APython', string)
if match:
print("pattern found inside the string")
else:
print("pattern not found")
输出
pattern found inside the string
这里,match包含了一个匹配对象。
re.subn()
re.subn()与re.sub()类似,不同之处在于它返回一个包含新字符串和替换次数的元组。
示例
#Program to remove all whitespaces
import re
#multiline string
string = 'abc 12\
de 23 \n f45 6'
print("Orginal String =",string)
#matches all whitespace characters
pattern = '\s+'
#empty string
replace = ''
new_string = re.subn(pattern, replace, string)
print("New String=",new_string)
输出
Orginal String = abc 12de 23
f45 6
New String= ('abc12de23f456', 4)
re.split()
re.split()提供一个字符串列表,在匹配存在的地方拆分字符串后,进行拆分。
示例
import re
string = 'Twelve:12 Eighty nine:89.'
pattern = '\d+'
result = re.split(pattern, string)
print(result)
输出
['Twelve:', ' Eighty nine:', '.']
如果没有找到匹配的模式,re.split() 返回一个包含原始字符串的列表。
你可以向 re.split() 方法传递 maxsplit 参数。它是将发生的最大分割数。
示例
import re
string = 'Twelve:12 Eighty nine:89 Nine:9.'
pattern = '\d+'
//maxsplit = 1
//split only at the first occurrence
result = re.split(pattern, string, 1)
print(result)
输出
['Twelve:', ' Eighty nine:89 Nine:9.']
顺便说一下,maxsplit的默认值是0,意味着所有可能的拆分。
re.sub()
re.sub()的语法如下:
re.sub(pattern, replace, string)
该方法返回一个字符串,其中匹配的出现将用替换变量的内容替换。
示例
#Program to remove all whitespaces
import re
#multiline string
string = 'abc 12\ de 23 \n f45 6'
#matches all whitespace characters
pattern = '\s+'
#empty string
replace = ''
new_string = re.sub(pattern, replace, string)
print(new_string)
输出
abc12\de23f456
如果没有找到匹配的模式,re.sub()方法将返回原始字符串。
您可以将count作为re.sub()方法的第四个参数传递。如果省略,结果为0。这将替换所有出现次数。
示例
import re
#multiline string
string = "abc 12\
de 23 \n f45 6"
#matches all whitespace characters
pattern = '\s+'
replace = ''
new_string = re.sub(r'\s+', replace, string, 1)
print(new_string)
输出
abc12de 23
f45 6
匹配对象
您可以使用dir()函数获取匹配对象的方法和属性。
一些常用的匹配对象的方法和属性包括:
match.group()
group()方法返回字符串中与之匹配的部分。
示例
import re
string = '39801 356, 2102 1111'
#Three digit number followed by space followed by two digit number
pattern = '(\d{3}) (\d{2})'
#match variable contains a Match object.
match = re.search(pattern, string)
if match:
print(match.group())
else:
print("pattern not found")
输出
801 35
在这里,match变量包含一个匹配对象。
我们的模式(\d{3}) (\d{2})有两个子组(\d{3})和(\d{2})。你可以获取这些被括号包围的子组的字符串部分。这是如何操作的−
>>> match.group(1)
'801'
>>> match.group(2)
'35'
>>> match.group(1, 2)
('801', '35')
>>> match.groups()
('801', '35')
match.start(), match.end() and match.span()
The start() function returns the index of the start of the matched substring. Similarly, end() returns the end index of the matched substring.
>>> match.start()
2
>>> match.end()
8
The span() function returns a tuple containing start and end index of the matched part.
>>> match.span()
(2, 8)
match.re and match.string
The re attribute of a matched object returns a regular expression object. Similarly, string attribute returns the passed string.
>>> match.re
re.compile('(\d{3}) (\d{2})')
>>> match.string
'39801 356, 2102 1111'
我们已经涵盖了re模块中定义的所有常用方法。如果你想了解更多,请访问Python 3 re模块。
在正则表达式之前使用r前缀
当在正则表达式之前使用r或R前缀时,它表示为原始字符串。例如,’\n’代表一个换行符,而r’\n’表示两个字符:一个反斜杠\后跟一个n。
反斜杠\用于转义包括所有元字符在内的各种字符。然而,使用r前缀使\被视为普通字符。
示例
import re
string = '\n and \r are escape sequences.'
result = re.findall(r'[\n\r]', string)
print(result)
输出
['\n', '\r']
结论
因此,这些都是我们尝试使用一些有趣的示例来解释的最基本和关键的正则表达式概念。其中有一些是虚构的,但大部分是真实的问题,我们在清理数据时遇到的问题,所以在将来,如果您遇到问题,只需再次回顾示例;您可能会在那里找到解决方案。