使用正则表达式匹配两个字符串之间的文本 [英] Match text between two strings with regular expression
本文介绍了使用正则表达式匹配两个字符串之间的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用一个正则表达式来匹配两个字符串之间的任何文本:
Part 1. Part 2. Part 3 然后更多文字
在此示例中,我想搜索第 1 部分"和第 3 部分",然后获取介于两者之间的所有内容:.第 2 部分."
我使用的是 Python 2x.
解决方案
使用 re.search
或者使用 re.findall
,如果出现不止一次.
I would like to use a regular expression that matches any text between two strings:
Part 1. Part 2. Part 3 then more text
In this example, I would like to search for "Part 1" and "Part 3" and then get everything in between which would be: ". Part 2. "
I'm using Python 2x.
解决方案
Use re.search
>>> import re
>>> s = 'Part 1. Part 2. Part 3 then more text'
>>> re.search(r'Part 1\.(.*?)Part 3', s).group(1)
' Part 2. '
>>> re.search(r'Part 1(.*?)Part 3', s).group(1)
'. Part 2. '
Or use re.findall
, if there are more than one occurances.
这篇关于使用正则表达式匹配两个字符串之间的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文