正则表达式的圆括号和中括号的区别

xiaoxiao2021-02-28  176

现象

String regex = ".*\\b(bug|fix|error|fail|leak|resolve|miss|correct|ensure|should|#\\d*)[es|ed|s|ly|ing|d]?\\b.*"; Pattern bug = Pattern.compile(regex, Pattern.CASE_INSENSITIVE); Matcher m = bug.matcher(message); if(m.find()) return true; return false;

使用串Fixes-most-inspector-warnings 来匹配的时候,无法匹配,但是将后面的中括号改为圆括号则可以匹配(es|ed|s|ly|ing|d),思考两者的区别

原因

[ ]中括号里面的字符都是单独的,也就是es|ed被当做五个独立的字符,而不是es或者ed,而()圆括号则表示这是一个分组,分组里的|有或者的含义

验证

public static void testExpression(){ String regex = "[a|b]"; Pattern p = Pattern.compile(regex); String check = "|"; System.out.println(p.matcher(check).find()); } public static void testExpression2(){ String regex = "(a|b)"; Pattern p = Pattern.compile(regex); String check = "|"; System.out.println(p.matcher(check).find()); }

运行上述例子可以得到结果 True False,符合原因中的解释。

转载请注明原文地址: https://www.6miu.com/read-39366.html

最新回复(0)