2016-08-02 134 views
3

比方说,我们有一个字符串如何在多行字符串中捕获特定字符和字符串之间的字符串? 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个字符串?

+0

所以,我试图修复你的代码块,你能确认它们是否符合你的意图吗? – jedwards

+0

谢谢。这是我想要的 – Sam

+1

这里有一个伟大的正则表达式生成器帮助您测试https://regex101.com/#python – ti7

回答

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的评论)而不是testWhere

    \b 匹配空字符串,但只在开头或词的末尾....

注意,可以阅读了关于re.DOTALL,因为我认为那是真的你想要什么。 DOTALL.字符包含换行符,而MULTILINE让锚点(^,$)匹配行的开始和结束,而不是整个字符串。考虑到你不使用锚点,我认为DOTALL更合适。

+1

非常感谢。这正是我所期待的。我也很欣赏这个解释。我会尽快接受这个答案。 – Sam

+1

请注意,这将与'tester','testerfield','testman'中的'test'匹配(也就是你的想法) - 也应用单词边界:'\ btest \ b'。 – Jan

+0

@Jan,多数民众赞成在一个好主意,将编辑。 – jedwards

相关问题