Python正则表达式模块(re)简介

author:skate
time:2014/10/13


Python正则表达式模块(re)简介


一、Python中转义字符
    正则表达式使用反斜杠" \ "来代表特殊形式或用作转义字符,这里跟Python的语法冲突,因此,Python用" \\\\ "表示正则表达式中的" \ ",
因为正则表达式中如果要匹配" \ ",需要用\来转义,变成" \\ ",而Python语法中又需要对字符串中每一个\进行转义,所以就变成了" \\\\ "。
    Python特别设计了原始字符串(raw string),需要注意的是,在写文件路径的时候就不要使用raw string了,raw string就是用'r'作为字符串
的前缀,如 r"\n":表示两个字符"\"和"n",而不是换行符了。Python中写正则表达式时推荐使用这种形式。

二、正则表达式元字符说明
.    匹配除换行符以外的任意字符
^    匹配字符串的开始
$    匹配字符串的结束
[]   用来匹配一个指定的字符类别
+    用来匹配前一个字符1次或无限次
?   对于前一个字符字符重复0次到1次
*    对于前一个字符重复0次到无穷次
{}   对于前一个字符重复m次
{m,n} 对前一个字符重复为m到n次
\d   匹配数字,相当于[0-9]
\D   匹配任何非数字字符,相当于[^0-9]
\s   匹配任意的空白符,相当于[ fv]
\S   匹配任何非空白字符,相当于[^ fv]
\w   匹配任何字母数字字符,相当于[a-zA-Z0-9_]
\W   匹配任何非字母数字字符,相当于[^a-zA-Z0-9_]
\b   匹配单词的开始或结束


三、基本使用

>>> import re    //导入模块
>>> dir(re)      //查看正则模块包含的方法
['DEBUG', 'DOTALL', 'I', 'IGNORECASE', 'L', 'LOCALE', 'M', 'MULTILINE', 'S', 'Scanner', 'T', 'TEMPLATE', 'U', 'UNICODE', 'VERBOSE', 'X', '_MAXCACHE', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__version__', '_alphanum', '_cache', '_cache_repl', '_compile', '_compile_repl', '_expand', '_pattern_type', '_pickle', '_subx', 'compile', 'copy_reg', 'error', 'escape', 'findall', 'finditer', 'match', 'purge', 'search', 'split', 'sre_compile', 'sre_parse', 'sub', 'subn', 'sys', 'template']
>>>

提示:当我们不会用模块方法的时候用help
>>> help(re.search)
Help on function search in module re:

search(pattern, string, flags=0)
    Scan through string looking for a match to the pattern, returning
    a match object, or None if no match was found.
(END)

 

例子:

使用re的一般步骤是先将正则表达式的字符串形式编译为Pattern实例,然后使用Pattern实例处理文本并获得匹配结果(一个Match实例),
最后使用Match实例获得信息,进行其他的操作。


# encoding: UTF-8
import re

# 将正则表达式编译成Pattern对象
pattern = re.compile(r'hello')

# 使用Pattern匹配文本,获得匹配结果,无法匹配时将返回None
match = pattern.match('hello world!')

if match:
    # 使用Match获得分组信息
    print match.group()

参考:http://www.cnblogs.com/huxi/archive/2010/07/04/1771073.html

 

四、常用的正则表达式处理函数

1. search(string[, pos[, endpos]]) | re.search(pattern, string[, flags]):
这个方法用于查找字符串中可以匹配成功的子串。从string的pos下标处起尝试匹配pattern,如果pattern结束时仍可匹配,则返回一个Match对象;
若无法匹配,则将pos加1后重新尝试匹配;直到pos=endpos时仍无法匹配则返回None。 pos和endpos的默认值分别为0和len(string));re.search()
无法指定这两个参数,参数flags用于编译pattern时指定匹配模式。


>>> # encoding: UTF-8
... import re
>>>
>>> # 将正则表达式编译成Pattern对象
... pattern = re.compile(r'world')
>>>
>>> # 使用search()查找匹配的子串,不存在能匹配的子串时将返回None
... # 这个例子中使用match()无法成功匹配
... match = pattern.search('hello world!')
>>>
>>> if match:
...     # 使用Match获得分组信息
...     print match.group()
...
world
>>>


2. split(string[, maxsplit]) | re.split(pattern, string[, maxsplit]):
按照能够匹配的子串将string分割后返回列表。maxsplit用于指定最大分割次数,不指定将全部分割。

>>> import re
>>>
>>> p = re.compile(r'\d+')
>>> print p.split('one1two2three3four4')
['one', 'two', 'three', 'four', '']

 
 
 3. findall(string[, pos[, endpos]]) | re.findall(pattern, string[, flags]):
搜索string,以列表形式返回全部能匹配的子串。

>>> import re
>>>
>>> p = re.compile(r'\d+')
>>> print p.findall('one1two2three3four4')
['1', '2', '3', '4']


4. sub(repl, string[, count]) | re.sub(pattern, repl, string[, count]):
使用repl替换string中每一个匹配的子串后返回替换后的字符串。
当repl是一个字符串时,可以使用\id或\g<id>、\g<name>引用分组,但不能使用编号0。
当repl是一个方法时,这个方法应当只接受一个参数(Match对象),并返回一个字符串用于替换(返回的字符串中不能再引用分组)。
count用于指定最多替换次数,不指定时全部替换。

>>> import re
>>>
>>> p = re.compile(r'(\w+) (\w+)')
>>> s = 'i say, hello world!'
>>>
>>> print p.sub(r'\2 \1', s)
say i, world hello!
>>>
>>> def func(m):
...     return m.group(1).title() + ' ' + m.group(2).title()
...
>>> print p.sub(func, s)
I Say, Hello World!
>>>

 

 

---end----

 

参考:https://docs.python.org/2/library/re.html

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值