正则表达式在处理字符串方面或者文本的预处理方面是比较常用的,我现在所用的编程语言是python,所以在此主要介绍python的正则表达式模块。
re.match()
尝试从字符串的开始匹配一个模式,一定要注意是从字符串的开始!
#导入正则表达式模块
import re
text="JGood is a handsome boy, he is cool, clever, and so on..."
m=re.match(r'(\w+)\s',text)
#\w:匹配字母或数字或下划线或汉字
#\s:匹配任意的空白字符
if m:
print m.group(0),'\n',m.group(1)
else:
print "not match"
#返回的结果为:
>>>JGood
>>>JGood
re.match的函数原型为:re.match(pattern, string, flags)
- 第一个参数是正则表达式,这里为”(\w+)\s”,如果匹配成功,则返回一个Match,否则返回一个None;
- 第二个参数表示要匹配的字符串;
- 第三个参数是标致位,用于控制正则表达式的匹配方式,如:是否区分大小写,多行匹配等等。
re.search
在字符串内部查找模式匹配(这个和re.match不同),只找到第一个匹配然后返回,如果字符串没有匹配,则返回None
#导入模块
import re
#定义一个字符串
text = "JGood is a handsome boy, he is cool, clever, and so on..."
m=re.search(r'\shan(ds)omme\s',text)
if m:
print m.group(0),m.group(1)
else:
print 'Not Search'
返回的结果为:
>>>handsome ds
工作上有事情,未完待续…