Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
java string.matches需要匹配的字符串太多_Java_Regex_String - Fatal编程技术网

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

java string.matches需要匹配的字符串太多,java,regex,string,Java,Regex,String,以下代码: 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 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.replaceAll
String.replaceFirst
也这样做?这不是不一致吗?

试试,通过放置贪婪量词的
+
,您可以匹配整个
字符串。因为,
s
有多个字符。因此,要匹配,您应该选择一个将匹配的量词,多个
a-z
范围字符。对于
String.matches
,您不需要边界字符
^
$

String s = "casdfsad";
System.out.println(s.matches("[a-z]+"));// It will be true

不幸的是,
String
中没有
find
方法,您必须使用
Matcher.find()

将输出

true
true
false
编辑:如果要查找完整字符串而不需要正则表达式,可以使用
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
true
false

您正在尝试对Sring使用单字符正则表达式

你可以试试:

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

第三个匹配是因为*。String.matches不会隐式添加任何“^”和$以强制进行完整的字符串匹配。

是的,但我的问题是为什么必须匹配整个字符串,而不仅仅是子字符串。因为,s有多个字符。所以,为了匹配,你应该选择一个量词来匹配多个a-z范围字符。你说的不一致是什么意思
matches
不检查是否可以在字符串的某些部分找到正则表达式,但检查字符串是否完全匹配正则表达式。要检查是否可以在字符串中找到正则表达式,可以使用
Matcher
类中的
find()
方法
replaceAll
与其他
relace
方法一样工作,但使用regex作为参数,让与regex匹配的replace子字符串替换为其他方法
replaceFirst
的工作原理类似,但在首次更换后将停止。所有这些方法都很有意义,而且非常直观(至少对我来说)。