如何在多行字符串中捕获特定字符和字符串之间的字符串? Python的
问题描述:
比方说,我们有一个字符串如何在多行字符串中捕获特定字符和字符串之间的字符串? Python的
string="This is a test code [asdf -wer -a2 asdf] >(ascd asdfas -were)\
test \
(testing test) test >asdf \
test"
我需要获得字符之间的字符串>和字符串“测试”。
我试图
re.findall(r'>[^)](.*)test',string, re.MULTILINE)
但是我得到
(ascd asdfas -were)\ test \ (testing test) test >asdf.
不过,我需要:
(ascd asdfas -were)\
和
asdf
我怎样才能得到那2个字符串?
答
什么:
import re
s="""This is a test code [asdf -wer -a2 asdf] >(ascd asdfas -were)
test
(testing test) test >asdf
test"""
print(re.findall(r'>(.*?)\btest\b', s, re.DOTALL))
输出:
['(ascd asdfas -were)\n', 'asdf\n']
只有这种模式有些有趣的部分是:
-
.*?
,其中?
使得.*
“ungreedy”否则你会有一场单场比赛而不是两场比赛。 - 使用
\btest\b
作为“结束”标识符(请参阅下面的Jan的评论)而不是test
。 Where,\b
匹配空字符串,但只在开头或词的末尾....
注意,可以阅读了关于re.DOTALL
,因为我认为那是真的你想要什么。 DOTALL
让.
字符包含换行符,而MULTILINE
让锚点(^
,$
)匹配行的开始和结束,而不是整个字符串。考虑到你不使用锚点,我认为DOTALL
更合适。
所以,我试图修复你的代码块,你能确认它们是否符合你的意图吗? – jedwards
谢谢。这是我想要的 – Sam
这里有一个伟大的正则表达式生成器帮助您测试https://regex101.com/#python – ti7