Python正则表达式指南下半部
来源:互联网 发布:机顶盒vip破解软件 编辑:程序博客网 时间:2024/06/05 04:44
2.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
3.split(string[, maxsplit]) | re.split(pattern, string[, maxsplit]):
按照能够匹配的子串将string分割后返回列表。maxsplit用于指定最大分割次数,不指定将全部分割。
import
re
p
=
re.
compile
(r
'\d+'
)
print
p.split(
'one1two2three3four4'
)
### output ###
# ['one', 'two', 'three', 'four', '']
4.findall(string[, pos[, endpos]]) | re.findall(pattern, string[, flags]):
搜索string,以列表形式返回全部能匹配的子串。
import
re
p
=
re.
compile
(r
'\d+'
)
print
p.findall(
'one1two2three3four4'
)
### output ###
# ['1', '2', '3', '4']
5.finditer(string[, pos[, endpos]]) | re.finditer(pattern, string[, flags]):
搜索string,返回一个顺序访问每一个匹配结果(Match对象)的迭代器 。
import
re
p
=
re.
compile
(r
'\d+'
)
for
m
in
p.finditer(
'one1two2three3four4'
):
print
m.group(),
### output ###
# 1 2 3 4
6.sub(repl, string[, count]) | re.sub(pattern, repl, string[, count]):
使用repl替换string中每一个匹配的子串后返回替换后的字符串。
当repl是一个字符串时,可以使用\id或\g<id>、\g<name>引用分组,但不能使用编号0。
当repl是一个方法时,这个方法应当只接受一个参数(Match对象),并返回一个字符串用于替换(返回的字符串中不能再引用分组)。
- Python正则表达式指南下半部
- Python正则表达式指南
- Python正则表达式指南
- Python 正则表达式指南
- Python正则表达式指南
- python正则表达式指南
- python正则表达式指南
- Python正则表达式指南
- python 正则表达式指南
- Python正则表达式指南
- Python正则表达式指南
- python正则表达式指南
- Python正则表达式指南
- Python正则表达式指南
- Python正则表达式指南
- Python正则表达式指南
- Python正则表达式指南
- Python正则表达式指南
- php foreach用法和实例
- PHP开发经验总结
- Android文件选择器
- Python正则表达式指南上半部
- Python正则表达式指南中半部
- Python正则表达式指南下半部
- 用户态调试模型
- Python正则表达式指南下下半部
- CSS中的绝对定位与相对定位
- CSS浮动详解(1)
- float详解(2)
- 如何选购无线路由器
- max-width
- CSS定位属性Position详解