![](/img/trans.png)
[英]How to extract certain substring from a multi line string in Python?
[英]How do I capture string between certain Character and String in multi line String? Python
假设我们有一个字符串
string="This is a test code [asdf -wer -a2 asdf] >(ascd asdfas -were)\
test \
(testing test) test >asdf \
test"
我需要在字符>和字符串“test”之间获取字符串。
我试过了
re.findall(r'>[^)](.*)test',string, re.MULTILINE )
但是我得到了
(ascd asdfas -were)\ test \ (testing test) test >asdf.
但是我需要:
(ascd asdfas -were)\
和
asdf
我怎样才能获得这两个字符串?
关于什么:
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
。 哪里 ,
\\b
匹配空字符串,但仅限于单词的开头或结尾....
注意,它可能是在re.DOTALL
上re.DOTALL
,因为我认为这真的是你想要的。 DOTALL
让.
字符包括换行符,而MULTILINE
允许锚点( ^
, $
)匹配行的开头和结尾而不是整个字符串。 考虑到你不使用锚点,我认为DOTALL
更合适。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.