- import re
-
- text = "JGood is a handsome boy, he is cool, clever, and so on..."
- m = re.search(r'\shan(ds)ome\s' , text)
- if m:
- print m.group( 0 ), m.group( 1 )
- else :
- print 'not search'
import re text = "JGood is a handsome boy, he is cool, clever, and so on..." m = re.search(r'\shan(ds)ome\s', text) if m: print m.group(0), m.group(1) else: print 'not search'
re.search的函数原型为: re.search(pattern, string, flags)
每个参数的含意与re.match一样。
re.match与re.search的区别: re.match只匹配字符串的开始,如果字符串开始不符合正则表达式,则匹配失败,函数返回None;而re.search匹配整个字符串,直到找到一个匹配。
re.sub
re.sub用于替换字符串中的匹配项。下面一个例子将字符串中的空格 ' ' 替换成 '-' :
- import re
-
- text = "JGood is a handsome boy, he is cool, clever, and so on..."
- regex = re.compile(r'\w*oo\w*' )
- print regex.findall(text) #查找所有包含'oo'的单词
- print regex.sub( lambda m: '[' + m.group( 0 ) + ']' , text) #将字符串中含有'oo'的单词用[]括起来。
import re text = "JGood is a handsome boy, he is cool, clever, and so on..." regex = re.compile(r'\w*oo\w*') print regex.findall(text) #查找所有包含'oo'的单词 print regex.sub(lambda m: '[' + m.group(0) + ']', text) #将字符串中含有'oo'的单词用[]括起来。
更详细的内容,可以参考Python手册。