re模块是Python用来操作正则表达式的库
1.、re.match
re.match()只有在0位置匹配成功的话才有返回,如果不是开始位置匹配成功的话,match()就返回none。
函数语法:
re.match(pattern, string[, flags])
代码示例:
//r"\w+":表示匹配1个或无限个字母。
import re
text = 'pythontab'
m = re.match(r"\w+", text)
if m:
print(m.group(0))
else:
print('not match')
结果:
pythontab
import re
text = '@pythontab'
m = re.match(r"\w+", text)
if m:
print(m.group(0))
else:
print('not match')
结果:
not match
2、 re.search
search()会扫描整个字符串并返回第一个成功的匹配
import re
text = 'pythontab'
m = re.search(r"\w+", text)
if m:
print m.group(0)
else:
print 'not match'
结果:
pythontab
将text的值改为text = ‘@pythontab’也是返回同样的结果。
3、 re.sub
re.sub用于替换字符串中的匹配项。下面一个例子将字符串中的空格 ’ ’ 替换成 ‘-’ :
re.sub的函数原型为:re.sub(pattern, repl, string, count)
其中第二个函数是替换后的字符串;本例中为’-‘
第四个参数指替换个数。默认为0,表示每个匹配项都替换。
re.sub还允许使用函数对匹配项的替换进行复杂的处理。如:re.sub(r’\s’, lambda m: ‘[’ + m.group(0) + ‘]’, text, 0);将字符串中的空格’ ‘替换为’[ ]’。
import re
text = "JGood is a handsome boy, he is cool, clever, and so on..."
print re.sub(r'\s+', '-', text)
4、 re.split
split(string[, maxsplit]) | re.split(pattern, string[, maxsplit]):
按照能够匹配的子串将string分割后返回列表。maxsplit用于指定最大分割次数,不指定将全部分割。
import re
p = re.compile(r'\d+')//表示以1个数字或多个数字做分隔符
print p.split('a1b2c3d4')
输出:
[‘a’, ‘b’, ‘c’, ‘d’]
5、 re.findall
findall() 搜索string,以列表形式返回全部能匹配的子串。
p = re.compile(r'\d+')
print(p.findall('a11b2c3d4'))
结果:
[‘11’,’2’,’3’,’4’]
6、re.compile
re.compile
可以把正则表达式编译成一个正则表达式对象。可以把那些经常使用的正则表达式编译成正则表达式对象,这样可以提高一定的效率。