Skip to content

Files

Latest commit

9044e33 · Nov 21, 2019

History

History
142 lines (102 loc) · 3.38 KB

89.md

File metadata and controls

142 lines (102 loc) · 3.38 KB

正则表达式

原文: https://pythonspot.com/regular-expressions/

正则表达式本质上是嵌入在 Python 中的一种高度专业化的编程语言,它使您能够为想要匹配的可能字符串集指定规则。

在 Python 中,您需要re模块来使用正则表达式。 语法概述在此页面的底部。

匹配函数

匹配函数定义为:

re.match(pattern, string)

参数为:

参数 描述
pattern 正则表达式
string 输入字符串

如果要将字符串与正好为五个的数字序列匹配,可以使用以下代码:

#!/usr/bin/python
import re

input = raw_input("Enter an input string:")
m = re.match('\d{5}\Z',input)

if m:
    print("True")
else:
    print("False")

输出示例:

电子邮件验证正则表达式

我们可以使用相同的函数来验证电子邮件地址。 语法规则在re.compile和语法表中可见。

字符串 匹配
12345
12358
55555
123
123K5
5555555
#!/usr/bin/python
import re

input = raw_input("Enter an input string:")
m = re.match('[^@][email protected][^@]+\.[^@]+',input)

if m:
    print("True")
else:
    print("False")

搜索函数

搜索函数定义为:

re.search(pattern, string)

参数为:

参数 描述
pattern 正则表达式,定义要搜索的字符串
string 搜索空间

要搜索电子邮件地址是否在字符串中:

#!/usr/bin/python
import re

input = "Contact me by [email protected] or at the office."

m = re.search('[^@][email protected][^@]+\.[^@]+',input)

if m:
    print("String found.")
else:
    print("Nothing found.")

正则表达式示例

正则表达式的一些示例:

正则表达式语法

正则表达式语法概述:

示例 正则表达式
IP 地址 `(([2][5][0-5].)
电子邮件 [^@]+@[^@]+\.[^@]+
日期MM/DD/YY (\d+/\d+/\d+)
整数(正) (?<![-.])\b[0-9]+\b(?!\.[0-9])
整数 [+-]?(?<!\.)\b[0-9]+\b(?!\.[0-9])
浮点 `(?<=>)\d+.\d+
十六进制 \s–([0-9a-fA-F]+)(?:–)?\s
正则表达式 描述
\d 匹配任何十进制数字; 这相当于类[0-9]
\D 匹配任何非数字字符; 这等效于类[^0-9]
\s 匹配任何空白字符; 这等效于类[ \t\n\r\f\v]
\S 匹配任何非空白字符; 这等效于类[^ \t\n\r\f\v]
\w 匹配任何字母数字字符; 这等效于类[a-zA-Z0-9_]
\W 匹配任何非字母数字字符; 这等效于类[^a-zA-Z0-9_]
\Z 仅在字符串末尾匹配
[..] 匹配括号中的单个字符
[^..] 匹配任何不在方括号中的单个字符
. 匹配换行符以外的任何字符
$ 匹配字符串的结尾
* 匹配 0 个或更多重复
+ 1 次或多次重复
{m} 之前 RE 的确切 m 个副本应匹配。
| 匹配 A 或 B。
? 先前 RE 的 0 或 1 次重​​复
[a-z] 任何小写字符
[A-Z] 任何大写字符
[a-zA-Z] 任何字符
[0-9] 任何数字