情况是这样的:
我想使用Java删除所有匹配"//[^\n]*"
的内容,但也匹配"\"[^\n]*//[^\n\"]\""
的所有内容。几乎,我需要删除所有注释样式输入,除非它包含在字符串中。我尝试了正则表达式"(//[^\n]*)-(\"[^\n]*//[^\n]*\")"
,但这不能替代任何内容。
最佳答案
这是多年前来自Perl小组的,我对其进行了一些修改以保留格式。
有一个更简单的版本,它不保留格式。
由于保留,此方法使用多行模式。
另外,如果没有单引号引起来的字符串,请取出该部分。
它基本上匹配评论或非评论。
运行它;
设置多线模式
用$2
进行全局替换
就是这样。
# raw: ((?:(?:^[ \t]*)?(?:/\*[^*]*\*+(?:[^/*][^*]*\*+)*/(?:[ \t]*\r?\n(?=[ \t]*(?:\r?\n|/\*|//)))?|//(?:[^\\]|\\(?:\r?\n)?)*?(?:\r?\n(?=[ \t]*(?:\r?\n|/\*|//))|(?=\r?\n))))+)|("(?:\\[\S\s]|[^"\\])*"|'(?:\\[\S\s]|[^'\\])*'|(?:\r?\n|[\S\s])[^/"'\\\s]*)
# quoted: "((?:(?:^[ \\t]*)?(?:/\\*[^*]*\\*+(?:[^/*][^*]*\\*+)*/(?:[ \\t]*\\r?\\n(?=[ \\t]*(?:\\r?\\n|/\\*|//)))?|//(?:[^\\\\]|\\\\(?:\\r?\\n)?)*?(?:\\r?\\n(?=[ \\t]*(?:\\r?\\n|/\\*|//))|(?=\\r?\\n))))+)|(\"(?:\\\\[\\S\\s]|[^\"\\\\])*\"|'(?:\\\\[\\S\\s]|[^'\\\\])*'|(?:\\r?\\n|[\\S\\s])[^/\"'\\\\\\s]*)"
( # (1 start), Comments
(?:
(?: ^ [ \t]* )? # <- To preserve formatting
(?:
/\* # Start /* .. */ comment
[^*]* \*+
(?: [^/*] [^*]* \*+ )*
/ # End /* .. */ comment
(?: # <- To preserve formatting
[ \t]* \r? \n
(?=
[ \t]*
(?: \r? \n | /\* | // )
)
)?
|
// # Start // comment
(?: # Possible line-continuation
[^\\]
| \\
(?: \r? \n )?
)*?
(?: # End // comment
\r? \n
(?= # <- To preserve formatting
[ \t]*
(?: \r? \n | /\* | // )
)
| (?= \r? \n )
)
)
)+ # Grab multiple comment blocks if need be
) # (1 end)
| ## OR
( # (2 start), Non - comments
"
(?: \\ [\S\s] | [^"\\] )* # Double quoted text
"
| '
(?: \\ [\S\s] | [^'\\] )* # Single quoted text
'
| (?: \r? \n | [\S\s] ) # Linebreak or Any other char
[^/"'\\\s]* # Chars which doesn't start a comment, string, escape,
# or line continuation (escape + newline)
) # (2 end)
关于java - Java正则表达式查找除B之外的所有A,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30552593/