标签:span 一个 字符 输出 odi x11 方法 简单的 tle
所使用模块:re
对于Python使用正则一般都是先将正则表达式的字符串形式编译然后进行实例化。如下进行一个最简单的正则匹配
#encoding=utf-8 #by def import re pattern = re.compile(r‘hello‘) #实例化 if re.match(‘hello world‘): #使用pattern去匹配字符串 print "true" else: print "false"
输出:true
因为其已经匹配到了所以输出true
re模块除了拥有compile这个方法以外还有
实例方法[ | re模块方法]:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
# 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 |
|
1
2
3
4
5
6
7
|
import rep = re.compile(r‘\d+‘)print p.split(‘one1two2three3four4‘)### output #### [‘one‘, ‘two‘, ‘three‘, ‘four‘, ‘‘] |
|
1
2
3
4
5
6
7
|
import rep = re.compile(r‘\d+‘)print p.findall(‘one1two2three3four4‘)### output #### [‘1‘, ‘2‘, ‘3‘, ‘4‘] |
|
1
2
3
4
5
6
7
8
|
import rep = re.compile(r‘\d+‘)for m in p.finditer(‘one1two2three3four4‘): print m.group(),### output #### 1 2 3 4 |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
import rep = re.compile(r‘(\w+) (\w+)‘)s = ‘i say, hello world!‘print p.sub(r‘\2 \1‘, s)def func(m): return m.group(1).title() + ‘ ‘ + m.group(2).title()print p.sub(func, s)### output #### say i, world hello!# I Say, Hello World! |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
import rep = re.compile(r‘(\w+) (\w+)‘)s = ‘i say, hello world!‘print p.subn(r‘\2 \1‘, s)def func(m): return m.group(1).title() + ‘ ‘ + m.group(2).title()print p.subn(func, s)### output #### (‘say i, world hello!‘, 2)# (‘I Say, Hello World!‘, 2) |
标签:span 一个 字符 输出 odi x11 方法 简单的 tle
原文地址:http://www.cnblogs.com/xishaonian/p/7639449.html