[TOC]
正则表达式
正则表达式(regular expression)描述了一种字符串匹配的模式(pattern),可以用来检查一个串是否含有某种子串、将匹配的子串替换或者从某个串中取出符合某个条件的子串等。
一、[]: 一个字符集合
[]
被称为字符类,用于定义一个字符集合,匹配该集合中任意一个字符。 在方括号内列出所有可能匹配的字符,正则表达式会匹配方括号中任意一个字符。
特殊符号
含义
-
来表示一个字符范围
^
表示排除方括号中指定的字符,例如:[ ^0-9] 非数字
\d
[0-9]
\D
[^0-9]
\w
[a-zA-Z0-9_]
\W
[^a-zA-Z0-9_]
\s
匹配任意空白字符,包括空格、制表符、换行符等
\S
匹配任意非空白字符
\b
单词边界,匹配单词的开始或结束位置,例如:\bcat\b
匹配独立的单词 cat
,而不会匹配 category
中的 cat
\B
非单词边界,匹配不在单词开始或结束的位置,例如:\Bing\B
对于 string
中的 ing
会匹配,而对于 sing
则不匹配
二、{}: 重复次数
{}
被称为量词,用于指定前面的元素(字符、字符类或分组)出现的次数。
特殊符号
含义
+
{1, } 1次以上
*
{0,} 0次以上
?
{0,1} 0次或1次、注:跟在 *
、+
、{}
等后面时,表示非贪婪匹配
.
匹配任意一个字符(换行除外)
三、特殊符号
特殊符号
含义
^
匹配开始的字符串
$
匹配结尾的字符串
\
转译符,例如:\.
匹配 .
、\d
匹配任意数字(等价于 [0-9]
)
|
或者。例如:[a|b]
四、(): 分组
分组,将多个字符组合成一个整体
创建捕获组,保存匹配内容
创建非捕获组((?:)
)
反向引用(\数字
)
分组,将多个字符组合成一个整体
1 2 3 4 5 6 7 import re pattern = r'(ab){2}' text = 'abababc' result = re.findall(pattern, text)print (result)
创建捕获组,保存匹配内容
1 2 3 4 5 6 7 8 9 10 11 import re pattern = r'(\d{4})-(\d{2})-(\d{2})' text = 'Today is 2024-10-15.' result = re.search(pattern, text)if result: print ("Full match:" , result.group(0 )) print ("Year:" , result.group(1 )) print ("Month:" , result.group(2 )) print ("Day:" , result.group(3 ))
创建非捕获组((?:)
)
1 2 3 4 5 6 7 import re pattern = r'(?:abc|def)\d' text = 'abc1 def2 ghi3' result = re.findall(pattern, text)print (result)
反向引用(\数字
)
1 2 3 4 5 6 7 import re pattern = r'(\b\w+\b)\s+\1' text = 'hello hello world' result = re.findall(pattern, text)print (result)
五、代码示例 在Python
中,使用re
模块来实现正则表达式。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 import re regex = 'a' string = 'abc' if re.search(regex, string) is not None : print (string) string = '2014 was a good year, but 2025 will be better!' years = re.findall('[1-2][0-9]{3}' , string)print (years)
六、注意 正则表达式里使用\
作为转义字符
假如你需要匹配文本中的字符\
,name编程语言表示的正则表达式需要4个反斜杠\\\\
,前两个和后两个分别用于在编程语言中转义成反斜杠,转换成两个反斜杠后再在正则表达式中转义成一个反斜杠。Python中的原生字符串很好的解决了这个问题,这个例子中的正则表达式可以使用r"\\"
表示。同样,匹配一个数字的"\\d"
可以写成r"\d"
,不需要再担心是否漏写了反斜杠,写出来的表达式也更直观。
1 2 3 4 5 6 import reif re.search("\\\\" , "I have one nee\dle" ) is not None : print ("Match" )else : print ("Not Match" )
1 2 3 4 5 6 import reif re.search(r"\\" , "I have one nee\dle" ) is not None : print ("Match" )else : print ("Not Match" )