我的问题是关于Java中的正则表达式

时间:2018-12-30 06:21:30

标签: java regex

我想知道以下情况的正则表达式是什么?

我想从我的Java代码中找出多行注释,如下所示。

文本1 ::

/*
This is my multi-line comment.
This is second line of the comment.
*/

但是我不想找出下面的表达式。

文本2 ::

/**
Any method description.
*/

因此,我只想提取与文本1类似但与文本2类似的注释。

我尝试过此正则表达式:

/*([^*]|[\r\n]|(*+([^*/]|[\r\n])))**+/

有人可以帮我吗?

谢谢

1 个答案:

答案 0 :(得分:1)

使用时在线正则表达式工具,当整个正则表达式包含在其中时 斜线,您需要的正则表达式为:

\/\*(?!\*).+?\*\/

详细信息:

  • \/-斜杠(引号)。
  • \*-一次冒险(也被引用)。
  • (?!\*)-对星号的负向超前查询(引用)。
  • .+?-任意字符的非空序列,不需要的版本。 由于 DOTALL 选项,该序列还包括换行符。
  • \*\/-星号和斜线(均引用)。

但是在Java环境中:

  • 正则表达式不是用斜杠括起来,因此正则表达式中的斜杠需要 不被引用。
  • 任何反斜杠都必须写成两次

因此要包含在Java代码中的正则表达式应重写为:

/\\*(?!\\*).+?\\*/

下面有一个示例Java代码,用于处理源文本:

import java.util.*;
import java.lang.*;
import java.util.regex.*;

class Rextester {  
    public static void main(String args[]) {
        String src = "/*\n" +
            "This is my multi-line comment.\n" +
            "This is second line of the comment.\n" +
            "*/\n" +
            "/**\n" +
            "Any method description.\n" +
            "*/";
        Matcher m = Pattern.compile("/\\*(?!\\*).+?\\*/", Pattern.DOTALL).matcher(src);
        int cnt = 0;
        while (m.find()) {
            System.out.println(String.format("Found %d:\n%s", ++cnt, m.group()));
        }
    }
}

它打印:

Found 1:
/*
This is my multi-line comment.
This is second line of the comment.
*/

如您所见,只是第一条评论,省略了第二条。

作为练习,将以上代码中的"/**\n"更改为"/* *\n"(添加 星号之间有一个空格)。 然后运行您的代码,您将看到这次两者注释 之所以打印,是因为否定的超前检查有误 立即紧随第一个。