如何在多行字符串中捕获特定字符和字符串之间的字符串?Python

2024-09-30 07:24:29 发布

您现在位置: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

我怎样才能得到那两根绳子?你知道吗


Tags: 字符串testrea2stringiscodethis
1条回答
网友
1楼 · 发布于 2024-09-30 07:24:29

关于:

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”变为“ungreedy”,否则将有一个长匹配,而不是两个。你知道吗
  • 使用\btest\b作为“结束”标识符(参见下面Jan的评论)而不是testWhere

    \b Matches the empty string, but only at the beginning or end of a word....

注意,它可能正在阅读^{},因为我认为这才是你真正想要的。DOTALL.字符包含换行符,而^{}让锚(^$)匹配行的开始和结束,而不是整个字符串。考虑到您不使用锚定,我认为DOTALL更合适。你知道吗

相关问题 更多 >

    热门问题