带有示例的Python正则表达式?
正则表达式是一种编程语言,用于识别给定的字符(字符串)序列中是否存在模式。
正则表达式或Regex是一个字符序列,用于检查字符串是否包含指定的搜索模式。
正则表达式模块
要使用RegEx模块,python附带了名为re的内置包,我们需要使用正则表达式来使用它。要使用RegEx模块,只需导入re模块即可。
import re
示例
import re
txt = "Use of python in Machine Learning"
x = re.search("^Use.*Learning$", txt)
if (x):
print("YES! We have a match!")
else:
print("No match")输出结果
YES! We have a match!
正则表达式功能
re模块提供了几个功能,使我们可以搜索字符串以查找匹配项。
元字符
RegEx中的元字符是具有特殊含义的字符。
特殊序列
RegEx中的特殊序列是\,后跟以下所列字符之一,并具有特殊含义-
套装
RegEx中的set是在一对方括号[]中的一组字符,它们具有某些特殊含义。
范例-findall()
该findall()函数返回包含所有匹配项的列表。
#Print a list of all matches (“in”) from a text
import re
txt = "Use of python in Machine Learning"
x = re.findall("in", txt)
print(x)输出结果
['in', 'in', 'in']
在输出显示列表上方,按找到顺序包含所有匹配项。但是,如果找不到匹配项,则会显示一个空列表。
只需在上面的程序中更改以下行,即“模式”,该行就不在文本或字符串中。
x = re.findall("Hello", txt)输出结果
[]
示例-search()函数
该search()函数搜索字符串,如果找到匹配项,则返回匹配对象。
但是,如果有多个匹配项,则仅返回匹配项的第一个匹配项。
import re
txt = "Python is one of the most popular languages around the world"
searchObj = re.search("\s", txt)
print("The first white-space character is located in position: ", searchObj.start())输出结果
The first white-space character is located in position: 6
但是,如果找不到匹配项,则返回None。
示例-split()函数
split()RegEx中的函数返回一个列表,该列表在每次匹配时均已将字符串分割开-
# Split at each white-space character
import re
string = "Python is one of the most popular languages around the world"
searchObj = re.split("\s", string)
print(searchObj)结果
['Python', 'is', 'one', 'of', 'the', 'most', 'popular', 'languages', 'around', 'the', 'world']
示例-sub()函数
sub()RegEx中的功能是将匹配项替换为您选择的文本。
#Replace every white-space in the string with _:
import re
string = "Python is one of the most popular language around the world"
searchObj = re.sub("\s", "_", string)
print(searchObj)结果
Python_is_one_of_the_most_popular_language_around_the_world
匹配对象
RegEx中的match对象是包含有关搜索和结果信息的对象。在未找到匹配项的情况下,不返回任何值。
示例-搜索字符串并返回匹配对象。
import re
string = "Python is one of the most popular language around the world"
searchObj = re.search("on", string)
print(searchObj)结果
<_sre.SRE_Match object; span=(4, 6), match='on'>
匹配对象具有用于检索有关搜索和结果的信息的属性和方法。
.span()–返回一个元组,其中包含找到的匹配项的开始和结束位置。
.string–返回传递给函数的字符串。
.group()–返回字符串中匹配的部分。
示例-打印字符串中匹配的部分。
#Looks for any words that starts with the an upper case “P”: import re string = "Python is one of the most popular language around the world" searchObj = re.search(r"\bP\w+", string) print(searchObj)
结果
<_sre.SRE_Match object; span=(0, 6), match='Python'>