python匹配字符串的方法?这个问题可能是我们日常学习或工作经常见到的。希望通过这个问题能让你收获颇深。下面是小编给大家带来的参考内容,让我们一起来看看吧!

python 中如何匹配字符串?

1. re.match 尝试从字符串的起始位置匹配一个模式,如果不是起始位置匹配成功的话,match()就返回none。

importreline="thishdr-biz123modelserver456"pattern=r"123"matchObj=re.match(pattern,line)

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

importreline="thishdr-bizmodelserver"pattern=r"hdr-biz"m=re.search(pattern,line)

3. Python 的re模块提供了re.sub用于替换字符串中的匹配项。

importreline="thishdr-bizmodelargs=server"patt=r'args='name=re.sub(patt,"",line)

4. compile 函数用于编译正则表达式,生成一个正则表达式( Pattern )对象,供 match() 和 search() 这两个函数使用。

importrepattern=re.compile(r'\d+')

5. re.findall 在字符串中找到正则表达式所匹配的所有子串,并返回一个列表,如果没有找到匹配的,则返回空列表。

importreline="thishdr-bizmodelargs=server"patt=r'server'pattern=re.compile(patt)result=pattern.findall(line)

6. re.finditer 和 findall 类似,在字符串中找到正则表达式所匹配的所有子串,并把它们作为一个迭代器返回。

importreit=re.finditer(r"\d+","12a32bc43jf3")formatchinit:print(match.group())

PS:Python字符串匹配及正则表达式说明

解析url地址正则表达式:

regexp=(r'^(?P<scheme>[a-z][\w\.\-\+]+)?:(//)?'r'(?:(?P<username>\w+):(?P<password>[\w\W]+)@|)'r'(?P<domain>[\w-]+(?:\.[\w-]+)*)(?::(?P<port>\d+))?/?'r'(?P<path>\/[\w\.\/-]+)?(?P<query>\?[\w\.*!=&@%;:/+-]+)?'r'(?P<fragment>#[\w-]+)?$')match=re.search(regexp,url.strip(),re.U)ifmatchisNone:raiseValueError('Incorrenturl:{0}'.format(url))url_parts=match.groupdict()url='https://blog.csdn.net/weixin_40907382/article/明细/79654372'print(url_parts):{'scheme':'https','username':None,'password':None,'domain':'blog.csdn.net','port':None,'path':'/weixin_40907382/article/明细/79654372','query':None,'fragment':None}

感谢各位的阅读!看完上述内容,你们对python匹配字符串的方法大概了解了吗?希望文章内容对大家有所帮助。如果想了解更多相关文章内容,欢迎关注亿速云行业资讯频道。