gpt4 book ai didi

java string.matches 需要匹配太多的字符串

转载 作者:行者123 更新时间:2023-11-29 05:33:17 26 4
gpt4 key购买 nike

以下代码:

String s = "casdfsad";
System.out.println(s.matches("[a-z]"));
System.out.println(s.matches("^[a-z]"));
System.out.println(s.matches("^[a-z].*"));

输出

false
false
true

但这是为什么呢?我没有在任何模式的末尾指定任何 $String.matches 是否隐式添加 ^$ 以强制进行完整的字符串匹配?为什么?我是否可以禁用完整字符串匹配,或许可以使用其他方法?

编辑:

如果 String.matches 隐式添加 ^$,为什么不添加 String.replaceAllString.replaceFirst也这样做?这不是不一致吗?

最佳答案

很遗憾,String 中没有find 方法,您必须使用Matcher.find()

Pattern pattern = Pattern.compile("[a-z]");
Matcher matcher = pattern.matcher("casdfsad");
System.out.println(matcher.find());

会输出

true

编辑:如果您想查找完整的字符串并且不需要正则表达式,您可以使用String.indexOf(),例如

String someString = "Hello World";
boolean isHelloContained = someString.indexOf("Hello") > -1;
System.out.println(isHelloContained);

someString = "Some other string";
isHelloContained = someString.indexOf("Hello") > -1;
System.out.println(isHelloContained);

会输出

true
false

关于java string.matches 需要匹配太多的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20373255/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com