java中的模式和^模式$ regEx有什么区别?

时间:2012-10-29 05:19:55

标签: java regex pattern-matching

以下两个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

2 个答案:

答案 0 :(得分:1)

您将无法在所选字符串中看到差异

尝试使用: - "afdbtrue""tru"同时使用它们。两个字符串都与第一个模式不匹配。

^true* - >这意味着字符串应以t开头(Caret(^)表示字符串的开头),然后是ru,并且可以有0个或更多etru之后(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,因为trut开头,而0之后有e tru 。与trueee相同。那很好
  • 您的第3个系统会打印false,因为asdtrue不以t开头
  • 您的第4个系统会再次出现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