看看您try 的模式和示例字符串,我认为它应该以匹配点后跟数字结束.
在这种情况下,您可以使用捕获组:
\bSection 1\.1\s+([^.]+(?:\.[^.]+){0,3})\.+\d+$
Explanation个
\bSection 1\.1
匹配单词Section
,然后匹配1.1
\s+
个匹配1+空格字符
(
Capture group 1
[^.]+
个匹配1+个字符,而不是.
(?:\.[^.]+){0,3}
重复0-3次匹配.
,后跟1+个字符而不是.
)
关闭第一组
\.+\d+
匹配1+点和1+数字(使用\.*
匹配可选点)
$
字符串尾
Python demo.com/r/FuQbe3/1" rel="nofollow noreferrer">Regex demo|Python demo
返回捕获组1值的re.findall
的示例:
import re
pattern = r"\bSection 1\.1\s+([^.]+(?:\.[^.]+){0,3})\.+\d+$"
s = ("Section 1.1 Some String.........................10\n"
"Section 1.2 Some Other String...................11\n"
"Section 1.1 I want to catch Som.e Str.i.ng..9\n"
"Section 1.1 I want to catch Som.e..9\n"
"Section 1.1 I want to catch Som.e Str.i.ng9\n"
"Section 1.1 but not So.m.e Str.i.ng.9")
print(re.findall(pattern, s, re.M))
输出
['Some String', 'I want to catch Som.e Str.i.ng', 'I want to catch Som.e']