以下两个正则表达式有什么区别?两者都与 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(^)
表示字符串开头),后跟 r
和 u
,tru
后面可以有 0 个或多个 e
(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 和 secondary
sysout 将打印true
,因为tru
以t
开头,并且tru
之后有0
e
。与trueee
相同。这样就可以了 - 您的第三个系统输出将打印
false
,因为asdtrue
不以t
开头 - 您的第四个系统输出将再次返回
false
,因为它不完全是true
- 您的
第 5 和第 6
系统输出将再次打印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
- 参见Matcher documentation有关这些方法的更多详细信息。 ( Matcher#find 和 Matcher#matches )
关于java - java中pattern和^pattern$ regEx有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13116246/