Python 使用正则表达式匹配两个字符串之间的文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32680030/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 12:04:26  来源:igfitidea点击:

Match text between two strings with regular expression

pythonregexpython-2.x

提问by Carlos Mu?iz

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. "

在此示例中,我想搜索“第 1 部分”和“第 3 部分”,然后获取介于两者之间的所有内容:“。第 2 部分。”

I'm using Python 2x.

我正在使用 Python 2x。

采纳答案by Avinash Raj

Use re.search

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.

或者使用re.findall,如果出现不止一次。

回答by lord63. j

With regular expression:

使用正则表达式:

>>> import re
>>> s = 'Part 1. Part 2. Part 3 then more text'
>>> re.search(r'Part 1(.*?)Part 3', s).group(1)
'. Part 2. '

Without regular expression, this one works for your example:

没有正则表达式,这个适用于您的示例:

>>> s = 'Part 1. Part 2. Part 3 then more text'
>>> a, b = s.find('Part 1'), s.find('Part 3')
>>> s[a+6:b]
'. Part 2. '