繁体   English   中英

Java中的pattern和^ pattern $ regEx有什么区别?

[英]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(^)表示字符串的开头),后跟ru ,并且tru后面可以有0或多个eu*表示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 etru trueee相同。 那就好了
  • 您的第3个sysout将输出false ,因为asdtrue不以t开头
  • 您的第4次sysout将再次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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM