Regex匹配整个多行注释联合标记专用词

时间:2022-09-30 22:29:04

I've been trying to design this regex but for the life of me I could not get it to not match if */ was hit before the special word.

我一直在尝试设计这个regex,但是对于我来说,如果*/在这个特殊的词之前被击中,我就无法让它不匹配。

I'm trying to match a whole multi line comment only if it contains a special word. I tried negative lookaheads/behinds but I could not figure out how to do it properly.

我试图匹配一个完整的多行注释,只有当它包含一个特殊的词。我试了一些消极的想法,但是我不知道怎么做才好。

This is what I have so far: (?s)(/\*.+?special.+?\*/)

这是我迄今为止:(?)(/ \ *。+特别。+ ? \ * /)

Am I close or horribly off base? I tried including (?!\*/) unsuccessfully.

我离得近还是离得太远?我尝试过包括(?!\*/)但没有成功。

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

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

Edit: I had some redundant parts to the regex I removed.

编辑:我删除了regex的一些多余部分。

1 个解决方案

#1


2  

You were not totally off base:

你不是完全错了:

/\*                 # match /*
(?:(?!\*/)[\s\S])+? # match anything lazily, do not overrun */
special             # match special
[\s\S]+?            # match anything lazily afterwards
\*/                 # match the closing */

The technique is called a tempered greedy token, see a demo on regex101.com (mind the modifiers, e.g. x for verbose mode !).

该技术被称为调和贪婪令牌,请参阅regex101.com上的演示(注意修饰符,例如x表示详细模式!)


You might want to try another approach tough: analyze your document, grep the comments (using eg BeautifulSoup) and run string functions over them ( if "special" in comment...).

#1


2  

You were not totally off base:

你不是完全错了:

/\*                 # match /*
(?:(?!\*/)[\s\S])+? # match anything lazily, do not overrun */
special             # match special
[\s\S]+?            # match anything lazily afterwards
\*/                 # match the closing */

The technique is called a tempered greedy token, see a demo on regex101.com (mind the modifiers, e.g. x for verbose mode !).

该技术被称为调和贪婪令牌,请参阅regex101.com上的演示(注意修饰符,例如x表示详细模式!)


You might want to try another approach tough: analyze your document, grep the comments (using eg BeautifulSoup) and run string functions over them ( if "special" in comment...).