Python re模块
jopen
9年前
闲话不多,走一遍简单的代码!
#encoding=utf-8 import re s = "My Name is Candy!" print re.findall("\\b\w.+$",s) print re.findall("^\w.+$",s) 结果: C:\Python27\python.exe D:/ProjectSpace/file-example.py ['My Name is Candy!'] ['My Name is Candy!'] Process finished with exit code 0
\w : 匹配任意数字、字母、下划线
\W: 匹配任意非数字、字母、下划线
\b : 匹配字符串开头或结尾
\B : 匹配字符串开头或结尾
\s : 匹配空白符
\S : 匹配非空白符
\d : 匹配任意数字
\D: 匹配任意非数字
有了以上知识,我们下面就直接走几个例子!
匹配字符串内包含 Candy 或者 !的地方:
#encoding=utf-8 import re s = "My Name is Candy!" print re.findall("Candy|!",s) 结果: C:\Python27\python.exe D:/ProjectSpace/file-example.py ['Candy', '!'] Process finished with exit code 0
匹配字符串内所有内容:
#encoding=utf-8 import re s = """ My Name is Candy! Welcome To My Home! Are You ok? """ print re.findall("\\b\w.+\\b",s) 结果: C:\Python27\python.exe D:/ProjectSpace/file-example.py ['My Name is Candy', 'Welcome To My Home', 'Are You ok'] Process finished with exit code 0
匹配字符串内所有以问号结尾的内容:
#encoding=utf-8 import re s = """ My Name is Candy! Who tell You My Name? Welcome To My Home! Are You ok? """ for i in re.findall("(.+\?\n)",s): print re.sub("\\n.?",'',i) 结果: C:\Python27\python.exe D:/ProjectSpace/file-example.py Who tell You My Name? Are You ok? Process finished with exit code 0
匹配字符串内所有以‘W’开头的行的内容:
#encoding=utf-8 import re s = """ My Name is Candy! Who tell You My Name? Welcome To My Home! Are You ok? """ for i in re.findall("\\bW.+",s): print i 结果: C:\Python27\python.exe D:/ProjectSpace/file-example.py Who tell You My Name? Welcome To My Home! Process finished with exit code 0
匹配字符串内所有包含‘My’的行的内容:
#encoding=utf-8 import re s = """ My Name is Candy! Who tell You My Name? Welcome To My Home! Are You ok? """ for i in re.findall(".*My.+",s): print i 结果: C:\Python27\python.exe D:/ProjectSpace/file-example.py My Name is Candy! Who tell You My Name? Welcome To My Home! Process finished with exit code 0
哎! 半夜三更发的帖子, 今天就到这吧! 此处列举的也许不是最好的匹配方法,大家可以自己进行尝试。