python 正则re.search

re.search 扫描整个字符串并返回第一个成功的匹配。

 

上码:

import re

line = "Cats are smarter than dogs";

searchObj = re.search(r'(.*) are (.*?) .*', line)

if searchObj:
print("searchObj.group() :", searchObj.group())
print("searchObj.group(1):", searchObj.group(1))
print("searchObj.group(2):", searchObj.group(2))
else:
print("Nothing found!!")


运行结果:

F:\dev\python\python.exe F:/pyCharm/practice/config_dir/zip_demo.py
searchObj.group() : Cats are smarter than dogs
searchObj.group(1): Cats
searchObj.group(2): smarter

Process finished with exit code 0

 

 

 

码2:

import re
print(re.search('www', 'www.runoob.com').span())
print(re.search('com', 'www.runoob.com').span())

运行结果:

F:\dev\python\python.exe F:/pyCharm/practice/config_dir/zip_demo.py
(0, 3)
(11, 14)

Process finished with exit code 0

posted @ 2019-02-15 17:39  志不坚者智不达  阅读(4891)  评论(0编辑  收藏  举报