Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 带行注释,而不是url_Java - Fatal编程技术网

Java 带行注释,而不是url

Java 带行注释,而不是url,java,Java,假设我们想要预处理JSON字符串以去掉C风格的行注释。例如: 像这样: // this is a comment { // another comment true, "foo", // 3rd comment "http://www.abc.com" // comment after URL } 编写一个函数来剥离行注释 我尝试使用regex: replaceAll("(?:/\\*(?:[^*]|(?:\\*+[^*/]))*\\*+/)|(?://.*)","") 这将删除

假设我们想要预处理JSON字符串以去掉C风格的行注释。例如:

像这样:

// this is a comment

{ // another comment

 true, "foo", // 3rd comment

 "http://www.abc.com" // comment after URL

}
编写一个函数来剥离行注释

我尝试使用regex:

replaceAll("(?:/\\*(?:[^*]|(?:\\*+[^*/]))*\\*+/)|(?://.*)","")
这将删除url,并获得以下输出:

  { 
 true,foo , 
http:
}
我希望url,即我希望我的输出为 { 没错,福, }


感谢您的帮助

问题在于,在regexp
(?:/.*)
的最后一个子句中,您正在匹配
/
,但您要做的是匹配
/
,而不是匹配
:/

有一个解决方案是用这样的一对来代替你的规则:

// this is a comment

{ // another comment

 true, "foo", // 3rd comment

 "http://www.abc.com" // comment after URL

}
a) 当前面有一个非
字符时,匹配
/
[^:://.

b) 匹配
/
如果它位于行的开头:
^/.

试试这个:

    String input = "// this is a comment\r\n" + 
            "\r\n" + 
            "{ // another comment\r\n" + 
            "\r\n" + 
            " true, \"foo\", // 3rd comment\r\n" + 
            "\r\n" + 
            " \"http://www.abc.com\" // comment after URL\r\n" + 
            "\r\n" + 
            "}";

    System.out.println(input.replaceAll("(?:/\\*(?:[^*]|(?:\\*+[^*/]))*\\*+/)|[^:]//.*|^//.*",""));

您可以计算开始/结束引号的数量,以查看您当前是否在字符串中。如果字符串中某处有
\“
,则计算引号将失败。但是,您还必须计算反斜杠,因为
\\”
不会是引号。我认为可以编写一个复杂的正则表达式来处理所有这些问题,但此时最好使用JSON解析器,或者自己编写一个简单的解析器。正则表达式不能处理所有事情,复杂的正则表达式是程序员偏头痛的主要原因。我建议您通过添加对正则表达式所做更改的解释来扩展您的答案,以及它们为什么工作?