如何捕获相同的组以及不相同的组

问题描述 投票:0回答:1

我试图在代码中捕获两种类型的注释。评论的类型为/../和// ...

我的模式:r'(/ *。?* /)|(//。?/)/'

上述模式不捕获两个类似的多行注释组(/ ** /)。如果它们由单行注释组(// ...)分隔。

这种模式有什么问题?

p=re.compile(r'(/\*.*?\*/)|(//.*?)/')
s='/*first multiline*/ //other comment /*second multiline*/'

expected:
["/*first multiline*/",""]
["","//other comment "]
["/*second multiline*/",""]

Actual:
["/*first multiline*/",""]
["","//other comment "]

注意:我知道这对跨越多行的评论不起作用。我只是想了解给定输入的上述模式的问题

python regex python-2.x
1个回答
0
投票

用这个:

re.compile(r'(/\*.*?\*/)|(//[^/\r\n]+)', re.DOTALL)

但是:ぁzxswい

问题是你的第二个捕获组拿下你假设的匹配的第一个斜线之后的最后一次斜线:

https://regex101.com/r/T4cM98/3

然而,一旦删除斜线,由于非贪婪的r'(/\*.*?\*/)|(//.*?)/' ^ here 表示法,它将不会捕获比双?更多的东西,所以只需匹配//之后不是/的所有内容。

编辑:根据Wiktor的建议更新//和re.DOTALL。

© www.soinside.com 2019 - 2024. All rights reserved.