Python正则表达式(一):元字符

来源:互联网 发布:socket 网络调试工具 编辑:程序博客网 时间:2024/04/29 18:28

Python正则表达式元字符包括:. ^ $ * + ? { [ ] \ | ( )


.
匹配除换行符以外的任意一个字符


^
匹配行首


$
匹配行尾


?
重复0次或1次
等同于{0,1}


*
重复0次或更多次
等同于{0,}


+
重复1次或更多次
等同于{1,}


{n}
重复n次


{n,}
重复n次或更多次


{n,m}
重复n~m次


[a-z]
a~z中任意1个字符


[abc]
a、b、c中任意1个字符
>>> ref = re.compile("[abc]{1,3}")>>> print ref.match("caa").group()caa
说明:{1,3},每次都返回[abc]任取一个;而不是[abc]先取一个,然后{1,3};
为什么会是这样呢?随后的文章中,将详细阐述正则的匹配过程。

>>> ref = re.compile("[.$*+?{}|()]")>>> print ref.findall(".")['.']>>> print ref.findall("$")['$']>>> print ref.findall("*")['*']>>> print ref.findall("?")['?']>>> print ref.findall("(")['(']>>> print ref.findall("|")['|']>>> print ref.findall("+")['+']>>> print ref.findall("{")['{']
说明:除了"\"、"^"两个元字符,其他元字符在[]里,会被当成普通字符处理

>>> ref = re.compile("[\d]")>>> print ref.match("1").group()1>>> ref = re.compile("[^\d]")>>> print ref.match("a").group()a
说明:"\"仍然是转义字符;"^"则是 非,而不是匹配行首


转义字符
转义字符+特定字符 = 预设字符(下一篇将会详细阐述预设字符的特殊含义);预设字符被正则表达式赋予了特殊的含义,比如说\d代表[0-9];
不巧,Python的转义字符也是“\”,比如“\n”代表一个换行符;

那么正则表达式为了获得一个字符串“\”,需要用“\\\\”;
>>> ref = re.compile("\\\\")#先Python转义:每个"\\"得到一个"\";接着正则转义"\\"得到"\">>> print ref.match("\\\\").group()\

Python的转义以及正则的转义先后对字符串进行转义,会使我们的正则表达式复杂难懂。因此,我们十分推荐用raw语法:r"str"来取消Python转义。
>>> ref = re.compile(r"\\")>>> print ref.match(r"\\").group()\

()
分组
>>> ref = re.compile("(a(b(c)))d")>>> print ref.match("abcd").group()abcd>>> print ref.match("abcd").group(0)abcd>>> print ref.match("abcd").group(1)abc>>> print ref.match("abcd").group(2)bc>>> print ref.match("abcd").group(3)c>>> print ref.match("abcd").group(4)Traceback (most recent call last):  File "<stdin>", line 1, in <module>IndexError: no such group
说明:group()默认参数为0,关于分组的更多用法,我们将在后续文章中阐述。


|
或 相当于or
>>> ref = re.compile("[\d]{2}|[\w]{5}")>>> print ref.match("111").group()11>>> print ref.match("aaaaaaa").group()aaaaa

小结:所谓元字符,其实是正则表达式赋予了这些字符,特殊含义。当正则表达式遇到这些字符时,会把它当成XX来解释。元字符表达的含义,一般相对单一。
比如我们想匹配字母或数字,我们可能会写[a-zA-Z0-9],这样写实在麻烦,有没有更简单的表述呢?有:预设字符。
下一篇中,我们就来学习预设字符。

0 0