選択した文字列の違いはわかりません。
使用してみてください: -"afdbtrue"または"tru"それらの両方を使用してください。どちらの文字列も最初のパターンに一致しません。
^true*-> これは、文字列がt(は文字列の開始をCaret(^)意味する) で始まり、その後にrandが続くことを意味し、 (は 0 以上の u を意味する)の後には 0u以上あります。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
- で始まり、後にあるため、sysout
first and secondは出力されます。と同じ。それでいいでしょうtruetrut0 etrutrueee
- で始まらない
falseため、3 番目の sysout は出力されます。asdtruet
- あなたの 4 番目の sysoutは、
false正確ではないため、再び鳴ります。true
- 正確に一致しないため、sysouts
5th and 6thは再び出力されます。falsetrue
更新: -
OPが質問を変更した後:-
^(caret)文字列の先頭に一致
$(Dollar)文字列の末尾に一致します。
したがって、で始まり で終わる^true$文字列に一致します。したがって、この場合、との使用方法に違いはありません。truetruetrue^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メソッドを使用する場合は、2 つのパターンに違いがあります。これを試して: -
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