【问题标题】:How do I capture string between certain Character and String in multi line String? Python如何在多行字符串中捕获某些字符和字符串之间的字符串? Python
【发布时间】:2016-12-08 01:32:00
【问题描述】:

假设我们有一个字符串

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

我怎样才能得到那两个字符串?

【问题讨论】:

  • 所以,我试图修复你的代码块,你能确认它们是你想要的吗?
  • 谢谢。这就是我想要的
  • 这是一个很棒的正则表达式生成器,可以帮助您测试regex101.com/#python

标签: python regex python-2.7 python-3.x


【解决方案1】:

怎么样:

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']

这个模式唯一有点有趣的部分是:

  • .*?,其中? 使.* “不贪婪”,否则您将得到一个长匹配而不是两个。
  • 使用\btest\b 作为“结束”标识符(参见下面 Jan 的评论)而不是 testWhere,

    \b 匹配空字符串,但仅在单词的开头或结尾......

注意,它可能正在阅读re.DOTALL,因为我认为这真的是你想要的。 DOTALL. 字符包含换行符,而MULTILINE 让锚点(^$)匹配行的开头和结尾而不是整个字符串。考虑到您不使用锚点,我认为DOTALL 更合适。

【讨论】:

  • 非常感谢。这正是我一直在寻找的。我也很欣赏这个解释。我会尽快接受这个答案。
  • 请注意,这将匹配testertesterfieldtestman 中的test(你明白了) - 也应用字边界:\btest\b
猜你喜欢
  • 1970-01-01
  • 2020-04-29
  • 1970-01-01
  • 2019-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多