当split()函数正确地将字符串拆分为模式时,为什么matches()函数返回false? [重复]

时间:2022-09-21 15:46:05

This question already has an answer here:

这个问题在这里已有答案:

Desired output : Java 1 8 true Output produced by this code Java 1 8 false what should be done to return true value ? the pattern of the input is [string] [dot][digit][dot][digit].

期望的输出:Java 1 8 true此代码生成的输出Java 1 8 false应该做什么来返回真值?输入的模式是[string] [dot] [digit] [dot] [digit]。

String st=java 1.8;
String regex="[\\s\\.]";
Pattern p=Pattern.compile(regex);
String []s2=p.split(st);
for(String a:s2)
System.out.println(a);
System.out.println(p.matches(st,regex));

} }

1 个解决方案

#1


1  

You are splitting the string - thus it searches for a portion on your string for that regex.

您正在拆分字符串 - 因此它会在字符串中搜索该正则表达式的一部分。

When you use matches (which is static and the arguments are in reverse order), you are matching against the entire string.

当您使用匹配项(它是静态的并且参数的顺序相反)时,您将匹配整个字符串。

So for example:

例如:

System.out.println(Pattern.matches(regex, st));

where regex would change to ".+[\\s\\.].+" would print true.

正则表达式将更改为“。+ [\\ s \\。]。+”将打印为true。

#1


1  

You are splitting the string - thus it searches for a portion on your string for that regex.

您正在拆分字符串 - 因此它会在字符串中搜索该正则表达式的一部分。

When you use matches (which is static and the arguments are in reverse order), you are matching against the entire string.

当您使用匹配项(它是静态的并且参数的顺序相反)时,您将匹配整个字符串。

So for example:

例如:

System.out.println(Pattern.matches(regex, st));

where regex would change to ".+[\\s\\.].+" would print true.

正则表达式将更改为“。+ [\\ s \\。]。+”将打印为true。