以下两个 regEx 有什么区别?两者都匹配java中的确切字符串。
System.out.println("true".matches("true"));
System.out.println("true".matches("^true$")); // ^ means should start and $ means should end. So it should mean exact match true. right ?
两者都打印true。
以下两个 regEx 有什么区别?两者都匹配java中的确切字符串。
System.out.println("true".matches("true"));
System.out.println("true".matches("^true$")); // ^ means should start and $ means should end. So it should mean exact match true. right ?
两者都打印true。
您将无法看到所选字符串的差异。
尝试使用: -"afdbtrue"或"tru"同时使用它们。两个字符串都不匹配第一个模式。
^true*-> 这意味着字符串应该以t(Caret(^)表示字符串的开头) 开头,然后是rand ,并且后面u可以有 0 个或多个(表示 0 个或多个 u)etruu*
System.out.println("tru".matches("^true*")); // true
System.out.println("trueeeee".matches("^true*"));// true
System.out.println("asdtrue".matches("^true*")); // false
System.out.println("tru".matches("true")); // false
System.out.println("truee".matches("true")); // false
System.out.println("asdftrue".matches("true")); // false
first and secondsysout 将打印出来true,因为tru从 开始,t在0 e之后tru。与 相同trueee。那会好的false,因为asdtrue不以tfalse因为它不完全true5th and 6th系统输出将再次打印false,因为它们不完全匹配true更新: -
OP改变问题后: -
^(caret)在字符串的开头匹配$(Dollar)匹配字符串的末尾。因此,^true$将匹配以 开头true和结尾的字符串true。因此,现在在这种情况下,您使用的方式true和使用方式之间不会有任何区别。^true$
str.matches("true")将匹配一个完全是"true".
的字符串,str.matches("^true$")也将完全匹配"true",因为它以 . 开头和结尾"true"。
System.out.println("true".matches("^true$")); // true
System.out.println("This will not match true".matches("^true$")); // false
System.out.println("true".matches("true")); // true
System.out.println("This will also not match true".matches("true")); // false
更新: -
但是,如果使用Matcher.find方法,则两种模式会有所不同。尝试这个: -
Matcher matcher = Pattern.compile("true").matcher("This will be true");
Matcher matcher1 = Pattern.compile("^true$").matcher("This won't be true");
if (matcher.find()) { // Will find
System.out.println(true);
} else {
System.out.println(false);
}
if (matcher1.find()) { // Will not find
System.out.println(true);
} else {
System.out.println(false);
}
输出: -
true
false
^表示字符串的开头
$表示字符串的结尾
matches方法如果整个字符串都可以匹配,则仅返回 true
所以,"true"&"^true$"都只匹配一个单词,即true
但是,如果您使用find方法,那么以下将是有效的所以,
"true"将匹配那些在任何地方包含 true 的行
Is it true//match
How true//match
true is truth//match
not false//no match
"^true$"
将匹配任何只有一个单词的行true
true//match
true is truth//no match
it is true//no match