Java正则表达式与预期不匹配

时间:2017-04-14 15:24:14

标签: java regex

我最近在Java中使用正则表达式,我无法解决这个问题。

        Pattern p = Pattern.compile("[^A-Z]+");
        Matcher matcher = p.matcher("GETs");
        if (matcher.matches()) {
            System.out.println("Matched.");
        } else {
            System.out.println("Did not match.");
        }

结果:未匹配(意外结果)解释此

我得到输出“不匹配”。在阅读https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html时,这对我来说很奇怪, 我使用的是X +,匹配“一次或多次”。

我认为我的语言代码会是这样的:

“检查字符串”GETs“中是否有一个或多个不属于A到Z的字符。”

所以我期待以下结果:

“是的,在”GETs“中有一个不属于A-Z的角色,正则表达式是匹配。”

然而事实并非如此,我很困惑为什么会这样。 我尝试了以下方法:

        Pattern p = Pattern.compile("[A-Z]+");
        Matcher matcher = p.matcher("GETs");
        if (matcher.matches()) {
            System.out.println("Matched.");
        } else {
            System.out.println("Did not match.");
        }

结果:不匹配。 (预期结果)

        Pattern p = Pattern.compile("[A-Z]+");
        Matcher matcher = p.matcher("GET");
        if (matcher.matches()) {
            System.out.println("Matched.");
        } else {
            System.out.println("Did not match.");
        }

结果:匹配。 (预期结果)

请解释为什么我的第一个例子不起作用。

3 个答案:

答案 0 :(得分:6)

  仅当整个区域时,

Matcher.matches才会返回true   匹配模式。

     

对于您要查找的输出,请改用Matches.find

每个案例的说明:

Pattern p = Pattern.compile("[^A-Z]+");
Matcher matcher = p.matcher("GETs");
  if (matcher.matches()) {

失败,因为 整个地区 'GETs'不是小写

Pattern p = Pattern.compile("[A-Z]+");
Matcher matcher = p.matcher("GETs");
  if (matcher.matches()) {

此操作失败,因为 整个地区 'GETs'不是大写

Pattern p = Pattern.compile("[A-Z]+");
Matcher matcher = p.matcher("GET");
  if (matcher.matches()) {

整个区域'GET'是大写的,模式匹配。

答案 1 :(得分:1)

你是第一个正则表达式要求匹配任何不在A-Z大写范围内的字符。比赛是在小写" s"在GETs。

答案 2 :(得分:0)

如果您希望正则表达式匹配大写和小写,则可以使用以下代码:
String test = "yes"; String test2= "YEs"; test.matches("(?i).*\\byes\\b.*"); test2.matches("(?i).*\\byes\\b.*");

在两种情况下将返回true

相关问题