Python正则表达式十种相关的匹配方法
Python正则表达式需要各种各样的匹配,但是我们不能盲目的进行相匹配,下面就向大家介绍经常遇到的十种Python正则表达式匹配方式,希望大家有所收获。1.测试Python正则表达式是否 匹配字符串的全部或部分
[*]regex=ur"..." #正则表达式
[*]if re.search(regex, subject):
[*]do_something()
[*]else:
[*]do_anotherthing()
2.测试Python正则表达式是否匹配整个字符串
[*]regex=ur"...\Z" #正则表达式末尾以\Z结束
[*]if re.match(regex, subject):
[*]do_something()
[*]else:
[*]do_anotherthing()
3. 创建一个匹配对象,然后通过该对象获得匹配细节
[*]regex=ur"..." #正则表达式
[*]match = re.search(regex, subject)
[*]if match:
[*]# match start: match.start()
[*]# match end (exclusive): match.end()
[*]# matched text: match.group()
[*]do_something()
[*]else:
[*]do_anotherthing()
4.获取Python正则表达式所匹配的子串
[*]regex=ur"..." #正则表达式
[*]match = re.search(regex, subject)
[*]if match:
[*]result = match.group()
[*]else:
[*]result = ""
5. 获取捕获组所匹配的子串
[*]regex=ur"..." #正则表达式
[*]match = re.search(regex, subject)
[*]if match:
[*]result = match.group(1)
[*]else:
[*]result = ""
6. 获取有名组所匹配的子串
[*]regex=ur"..." #正则表达式
[*]match = re.search(regex, subject)
[*]if match:
[*]result = match.group("groupname")
[*]else:
[*]result = ""
7. 将字符串中所有匹配的子串放入数组中
[*]reresult = re.findall(regex, subject)
8.遍历所有匹配的子串
[*](Iterate over all matches in a string)
[*]for match in re.finditer(r"<(.*?)\s*.*?/\1>", subject)
[*]# match start: match.start()
[*]# match end (exclusive): match.end()
[*]# matched text: match.group()
9.通过Python正则表达式 字符串创建一个正则表达式对象
[*](Create an object to use the same regex for many
operations)
[*]rereobj = re.compile(regex)
10.用法1的Python正则表达式对象版本
[*]rereobj = re.compile(regex)
[*]if reobj.search(subject):
[*]do_something()
[*]else:
[*]do_anotherthing()
以上就是对Python正则表达式相关问题匹配的解决方案。
页:
[1]