概念
正则表达式:又称规则表达式。(英语:Regular Expression,在代码中常简写为regex、regexp或RE),计算机科学的一个概念。正则表达式通常被用来检索、替换那些符合某个模式(规则)的文本。
正则表达式是对字符串操作的一种逻辑公式,就是用事先定义好的一些特定字符、及这些特定字符的组合,组成一个“规则字符串”,这个“规则字符串”用来表达对字符串的一种过滤逻辑。
应用
我们用Python里边的re(regular express)模块进行测试。先说明re模块的一个基本使用方法:
re.search(pattern, string, flags=0)
其中pattern是模式串,string是文本串,flags是控制符,用于表示区分大小写等。例如re.search(‘hesor’,‘hesorchen’)得到的结果是:
<re.Match object; span=(0, 5), match='hesor'>
表示文本串的(0,5)与模式串匹配
接下来我们按照RE中的特定字符进行实例讲解
.
这个点可以匹配除了\n以外的任何字符,见示例:
import re
txt = '\thesorchen'
ans = re.search('.', txt)
print(ans)
# <re.Match object; span=(0, 1), match='\t'>
txt = '\nhesorchen'
ans = re.search('.', txt)
print(ans)
# <re.Match object; span=(1, 2), match='h'>
[]
我们可以在[]
中填入一些字符,用逗号隔开,表示匹配任意一个即可,例如:
import re
txt = '\thesorchen'
ans = re.search('[s,o]', txt)
print(ans)
# <re.Match object; span=(3, 4), match='s'>
也可以在其中用-连接两个字符,表示一个范围,例如:
import re
txt = '\thesorchen'
ans = re.search('[c-e]', txt)
print(ans)
# <re.Match object; span=(2, 3), match='e'>
txt = '\thesorchen'
ans = re.search('[c-ef-h]', txt)
print(ans)
# <re.Match object; span=(1, 2), match='h'>
{}
在{}
中填入数字n,表示前面的字符重复n次,例如:
import re
txt = 'heeeeeh'
ans = re.search('he{3}', txt)
print(ans)
# <re.Match object; span=(0, 4), match='heee'>
import re
txt = 'heeeeeh'
ans = re.search('he{1,2}', txt)
print(ans)
# <re.Match object; span=(0, 3), match='hee'>
txt = 'heeeeeh'
ans = re.search('he{3,10}', txt)
print(ans)
# <re.Match object; span=(0, 6), match='heeeee'>
()
()
中的分组表达式作为一个整体。示例:
import re
txt = 'hesorchenchen'
ans = re.search('(chen){2}', txt)
print(ans)
# <re.Match object; span=(5, 13), match='chenchen'>
*
*
前面的字符可以出现0到无限次
+
+
前面的字符可以出现1到无限次
?
?
前面的字符可以出现0次或1次
$
$
匹配字符串的末尾,示例:
import re
txt = 'heshes'
ans = re.search('hes$', txt)
print(ans)
# <re.Match object; span=(3, 6), match='hes'>
^
^
匹配字符串的开头,示例:
import re
txt = 'heshes'
ans = re.search('^hes', txt)
print(ans)
# <re.Match object; span=(0, 3), match='hes'>
|
|
表示条件或,左右两边匹配一项即可,示例:
import re
txt = '123hesorchen123'
ans = re.search('[a-z]hesorchen[a-z]|[0-9]hesorchen[0-9]', txt)
print(ans)
# <re.Match object; span=(2, 13), match='3hesorchen1'>
还有很多不是很重要的不细说,具体要用的再查询。