[英]Java regex that searches multi-line text excluding some string
我有一些代码:
String test = "int measure; \n" +
"void introduce() { \n" +
"while (line != null) { \n" +
"if(measure > 0) { \n" +
"System.out.println(smile); \n" +
"} \n" +
"}";
String functions = "^.*(?!(catch|if|while|try|return|finally|new|throw)).*$";
Pattern patternFunctions = Pattern.compile(functions);
Matcher matcherFunctions = patternFunctions.matcher(test);
while(matcherFunctions.find())
System.out.println(matcherFunctions.group());
这应该打印除第三和第四行以外的所有行,因为它们包含“ if”和“ while”字样。 但实际上,它什么也不打印。 每一个帮助将不胜感激。 谢谢。
更新:
谢谢你们的回答! 您的示例正在工作。 我还有一个问题:否定前瞻后,我想插入条件.*\\\\(.*\\\\).*\\\\{
这意味着文本包括.*<negotiation>.*(.*).*{
简单的方式,它应该从我的String test
打印第二行。 我试过这个正则表达式(?m)^.*(?!(catch|if|while|try|return|finally|new|throw).\\\\(.*\\\\).*\\\\{)*$
但是它无法正常工作。 你有什么建议?
尝试启用多行模式,如此处所示: https : //stackoverflow.com/a/6143347/584663
并且,在负向展望中添加点: https : //stackoverflow.com/a/2387072/584663
产生:( (?m)^((?!(catch|if|while|try|return|finally|new|throw)).)*$
它没有输出,因为您的正则表达式不正确。
您需要删除开始的.*
并将捕获或未捕获的组放置在负前瞻周围,并重建结束的.*
,以使圆点成为可能.
放在最后一个括号的前面,而量词*
放在$
锚点的最后一个括号的后面。
您需要使用m
修饰符(多行),使^
和$
定位符与每行的开头/结尾匹配。 我还添加了i
修饰符用于不区分大小写的匹配。
String functions = "(?im)^(?:(?!(?:catch|if|while|try|return|finally|new|throw)).)*$";
正则表达式:
(?im) set flags for this block (case-insensitive)
(with ^ and $ matching start and end of line)
^ the beginning of a "line"
(?: group, but do not capture (0 or more times)
(?! look ahead to see if there is not:
(?: group, but do not capture:
catch 'catch'
| OR
if 'if'
| OR
while 'while'
| OR
try 'try'
| OR
return 'return'
| OR
finally 'finally'
| OR
new 'new'
| OR
throw 'throw'
) end of grouping
) end of look-ahead
. any character except \n
)* end of grouping
$ before an optional \n, and the end of a "line"
请参阅Working demo
"^.*(?!(catch..."
删除第一个.*
,因为它允许if
和while
! 工作代码:
String functions = "^((?!(catch|if|while|try|return|finally|new|throw))).*$";
Pattern patternFunctions = Pattern.compile(functions, Pattern.MULTILINE);
Matcher matcherFunctions = patternFunctions.matcher(test);
有关java.util.regex.Pattern.Multiline的更多信息
在多行模式下,表达式^和$分别在行终止符或输入序列的结尾之后或之前匹配。 默认情况下,这些表达式仅在整个输入序列的开头和结尾匹配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.