[英]What is difference between pattern and ^pattern$ regEx in java?
跟着两个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(^)
表示字符串的开头),后跟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 and second
系统输出将打印true
的,因为tru
开头t
并有0
e
后tru
。 与trueee
相同。 那就好了 false
,因为asdtrue
不以t
开头 false
因为它不完全true
5th and 6th
sysout将再次输出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
方法如果可以匹配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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.