且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-11-12 09:58:55

使用 re.search

>>>进口重新>>>s = '第 1 部分.第 2 部分.第 3 部分然后更多的文字'>>>re.search(r'Part 1\.(.*?)Part 3', s).group(1)' 第2部分. '>>>re.search(r'Part 1(.*?)Part 3', s).group(1)'.第2部分. '

或者使用 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.