Python 中的正则表达式

正则表达式这个术语通常被简称为正则表达式。正则表达式是定义搜索模式的字符序列,主要用于在搜索引擎和文本处理器中执行查找和替换操作。

Python 通过作为标准库的一部分捆绑的re模块提供正则表达式功能。

原始字符串

Python re 模块中的不同函数使用原始字符串作为参数。当前缀为“R”或“R”时,普通的字符串成为原始字符串。

Example: Raw String

>>> rawstr = r'Hello! How are you?'
>>> print(rawstr)
Hello! How are you? 

正常字符串和原始字符串的区别在于 print() 函数中的正常字符串翻译转义字符(如\n\t等)。)的值,而原始字符串中的值则不是。

Example: String vs Raw String

str1 = "Hello!\nHow are you?"
print("normal string:", str1)
str2 = r"Hello!\nHow are you?"
print("raw string:",str2) 

Output

normal string: Hello!
How are you?
raw string: Hello!\nHow are you? 

在上面的例子中,str1(正常字符串)中的\n被翻译为下一行中正在打印的换行符。 但是,它在str2中被印成了\n——一根生弦。

元字符

当某些字符作为部分模式匹配字符串出现时,它们具有特殊的含义。在 Windows 或 Linux DOS 命令中,我们使用*和?-它们类似于元角色。Python 的 re 模块使用以下字符作为元字符:

*。^ $ + ?[ ] \ | ( )**

当一组字母数字字符放在方括号[]内时,目标字符串与这些字符匹配。 方括号中可以列出一系列字符或单个字符。例如:

模式 描述
[abc] 匹配任意字符 a、b 或 c
[a-c] 它使用一个范围来表示同一组字符。
[a-z] 仅匹配小写字母。
[0-9] 只匹配数字。

下列特定的字符带有特定的含义。

模式 描述
\d 匹配任何十进制数字;这相当于类[0-9]。
\D 匹配任何非数字字符
\s 匹配任何空白字符
\S 匹配任何非空白字符
\w 匹配任何字母数字字符
\W 匹配任何非字母数字字符。
匹配除换行符“\n”以外的任何单个字符。
将模式的 0 或 1 匹配到它的左边
+ 在其左侧出现一个或多个图案
* 该模式在其左侧出现 0 次或更多次
\b 词与非词的界限。/b 与/B 相反
[..] 匹配方括号中的任何单个字符
\ 它用于特殊含义的字符,如。匹配加号的句点或+。
{n,m} 匹配前面的至少 n 次和最多 m 次出现
a| b 匹配 a 或 b

re.match()函数

re模块中的这个函数试图找出指定的模式是否出现在给定字符串的开头。

re.match(pattern, string)

如果给定的模式不在开头,则函数返回无,如果找到匹配的对象,则返回匹配的对象。

Example: re.match()

from re import match

mystr = "Welcome to TutorialsTeacher"
obj1 = match("We", mystr)
print(obj1)
obj2 = match("teacher", mystr)
print(obj2) 

Output

<re.Match object; span=(0, 2), match='We'>
None 

匹配对象具有startend属性。

Example:

>>> print("start:", obj.start(), "end:", obj.end()) 

Output

start: 0 end: 2 

下面的示例演示了如何使用字符范围来确定一个字符串是否以“W”开头,后跟一个字母。

Example: match()

from re import match

strings=["Welcome to TutorialsTeacher", "weather forecast","Winston Churchill", "W.G.Grace","Wonders of India", "Water park"]

for string in strings:
    obj = match("W[a-z]",string)
    print(obj) 

Output

<re.Match object; span=(0, 2), match='We'>
None
<re.Match object; span=(0, 2), match='Wi'>
None
<re.Match object; span=(0, 2), match='Wo'>
<re.Match object; span=(0, 2), match='Wa'> 

re.search()函数

re.search()函数在给定字符串的任意位置搜索指定的模式,并在第一次出现时停止搜索。

Example: re.search()

from re import search

string = "Try to earn while you learn"

obj = search("earn", string)
print(obj)
print(obj.start(), obj.end(), obj.group())
7 11 earn 

Output

<re.Match object; span=(7, 11), match='earn'> 

该函数还返回具有开始和结束属性的Match对象。它还给出了一组字符,该模式是其中的一部分。

re.findall()函数

search()功能相反,findall()继续搜索模式,直到目标字符串用尽。对象返回所有匹配项的列表。

Example: re.findall()

from re import findall

string = "Try to earn while you learn"

obj = findall("earn", string)
print(obj) 

Output

['earn', 'earn'] 

这个函数可以用来获取一个句子中的单词列表。为此,我们将使用\W*模式。我们还会检查哪些单词没有元音。

Example: re.findall()

obj = findall(r"\w*", "Fly in the sky.")
print(obj)

for word in obj:
    obj= search(r"[aeiou]",word)
    if word!='' and obj==None:
        print(word) 

Output

['Fly', '', 'in', '', 'the', '', 'sky', '', '']
Fly
sky 

re.finditer()函数

re.finditer()函数返回目标字符串中所有匹配项的迭代器对象。对于每个匹配的组,可以通过 span()属性获得开始和结束位置。

Example: re.finditer()

from re import finditer

string = "Try to earn while you learn"
it = finditer("earn", string)
for match in it:
    print(match.span()) 

Output

(7, 11)
(23, 27) 

re.split()函数

re.split()功能的工作原理类似于 Python 中str对象的 split() 方法。 每次发现空白时,它都会拆分给定的字符串。在上面的findall()获取所有单词的例子中,列表还包含作为单词的每个空格。 被re模块中的split()功能取消。

Example: re.split()

from re import split

string = "Flat is better than nested. Sparse is better than dense."
words = split(r' ', string)
print(words) 

Output

['Flat', 'is', 'better', 'than', 'nested.', 'Sparse', 'is', 'better', 'than', 'dense.'] 

重新编译()函数

re.compile()函数返回一个模式对象,可以在不同的正则表达式函数中重复使用。在下面的例子中,一个字符串“is”被编译以获得一个模式对象,并接受search()方法。

Example: re.compile()

from re import *

pattern = compile(r'[aeiou]')
string = "Flat is better than nested. Sparse is better than dense."
words = split(r' ', string) 
for word in words:
    print(word, pattern.match(word)) 

Output

Flat None
is <re.Match object; span=(0, 1), match='i'>
better None
than None
nested. None
Sparse None
is <re.Match object; span=(0, 1), match='i'>
better None
than None
dense. None 

相同的模式对象可以在搜索带有元音的单词时重复使用,如下所示。

Example: search()

for word in words:
    print(word, pattern.search(word)) 

Output

Flat <re.Match object; span=(2, 3), match='a'>
is <re.Match object; span=(0, 1), match='i'>
better <re.Match object; span=(1, 2), match='e'>
than <re.Match object; span=(2, 3), match='a'>
nested. <re.Match object; span=(1, 2), match='e'>
Sparse <re.Match object; span=(2, 3), match='a'>
is <re.Match object; span=(0, 1), match='i'>
better <re.Match object; span=(1, 2), match='e'>
than <re.Match object; span=(2, 3), match='a'>
dense. <re.Match object; span=(1, 2), match='e'> 

本文链接:https://my.lmcjl.com/post/7817.html

展开阅读全文

4 评论

留下您的评论.