java - java中pattern和^pattern$ regEx有什么区别?

标签 java regex pattern-matching

以下两个正则表达式有什么区别?两者都与 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(^) 表示字符串开头),后跟 rutru 后面可以有 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,因为 trut 开头,并且 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

关于java - java中pattern和^pattern$ regEx有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13116246/

相关文章:

java - JScrollPane 中的绝对布局面板

c# - 拆分一个由前导数字和之后的所有内容组成的字符串

MySQL 模式匹配 - 寻找匹配

pattern-matching - Agda 2.5.1.2 中模式匹配失败

scala - 如何避免在 Scala 中调用 asInstanceOf

java - 如何删除java中最后输入的值?

Java:按两列对多维进行排序并将特定行设置在顶部

英国电话号码的正则表达式

java - Java 中的正则表达式,用于匹配新行中出现结尾的模式

java - Android/Firebase - 检查您是否订阅了主题