如何在单行源代码注释之间提取文本?

时间:2022-09-13 16:20:02

I have the following regex to match source code comments:

我有以下正则表达式来匹配源代码注释:

private Pattern parser = Pattern.compile("^\\s*((?:/\\*(?:[^*]|(?:\\*+[^*/]))*\\*+/)|(?://.*))\\s*$");

This regex will match these types of comments:

这个正则表达式将匹配这些类型的注释:

// Comment
/* Comment */
/******** Comment ********/

It is very important that this regular expression matches also comments with indentation before and after the comment.

非常重要的是,此正则表达式还会在注释之前和之后匹配带缩进的注释。

Now I want to create capturing groups so I can easily access the text inside the comment.

现在我想创建捕获组,以便我可以轻松访问注释中的文本。

I tried to remove the non capturing groups but that didn't work as expected. How can I extend this regular expression in order to access the text inside the comment?

我试图删除非捕获组,但是没有按预期工作。如何扩展此正则表达式以访问注释中的文本?

1 个解决方案

#1


2  

If I understand you correctly, you want to remove the comment notation and the text from the comment, these two regular expressions will identify comments, and their text, so that you can remove them.

如果我理解正确,您想要从注释中删除注释表示法和文本,这两个正则表达式将识别注释及其文本,以便您可以删除它们。

\/\*([\S\s]+?)\*\/

(?s)/\*.*?\*/

These two will remove 3 types of comment

这两个将删除3种类型的评论

/**** Test ****/

/*
 *
 *  Here is another comment
 *
 *
 */

 /* Comment 




 */

This regex will remove the following types of comment

此正则表达式将删除以下类型的注释

//.*$

your code //Comment Comment

Example in NP++

NP ++中的示例

如何在单行源代码注释之间提取文本?

#1


2  

If I understand you correctly, you want to remove the comment notation and the text from the comment, these two regular expressions will identify comments, and their text, so that you can remove them.

如果我理解正确,您想要从注释中删除注释表示法和文本,这两个正则表达式将识别注释及其文本,以便您可以删除它们。

\/\*([\S\s]+?)\*\/

(?s)/\*.*?\*/

These two will remove 3 types of comment

这两个将删除3种类型的评论

/**** Test ****/

/*
 *
 *  Here is another comment
 *
 *
 */

 /* Comment 




 */

This regex will remove the following types of comment

此正则表达式将删除以下类型的注释

//.*$

your code //Comment Comment

Example in NP++

NP ++中的示例

如何在单行源代码注释之间提取文本?