以下两个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 。
答案 0 :(得分:1)
您将无法在所选字符串中看到差异。
尝试使用: - "afdbtrue"
或"tru"
同时使用它们。两个字符串都与第一个模式不匹配。
^true*
- >这意味着字符串应以t
开头(Caret(^)
表示字符串的开头),然后是r
和u
,并且可以有0个或更多e
在tru
之后(u*
表示0或更多u)
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 second
系统会打印true
,因为tru
以t
开头,而0
之后有e
tru
。与trueee
相同。那很好false
,因为asdtrue
不以t
开头false
,因为它不完全是true
5th 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
输出: -
{{1}}
答案 1 :(得分:0)
^
表示字符串的开头
$
表示字符串的结尾
matches
方法如果可以匹配WHOLE字符串,则返回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