【问题标题】:How to check matches pattern in java如何在java中检查匹配模式
【发布时间】:2015-10-27 18:48:05
【问题描述】:

我想匹配 "sec 30-31" 这样的模式。但它不适合我。

我正在使用如下匹配模式。

private boolean checkConstraint(String inputValue) {
    inputValue = inputValue.trim();
    if (inputValue.matches("[\\>][\\s]*[\\d]*") || inputValue.matches("[\\<][\\s]*[\\d]*") || inputValue.matches("[\\d]*[\\s]*[-][\\s]*[\\d]*")
            || inputValue.matches("[\\=][\\s]*[\\d]*") || inputValue.matches("[\\=][\\s]*[\\w]*") || inputValue.matches("[\\d]*")
            || inputValue.matches("[\\w]*") || inputValue.matches("[\\d]*[\\s]*[|][\\s]*[\\d]*")
            || inputValue.matches("[\\w]*[\\s]*[|][\\s]*[\\w]*") || inputValue.matches("[\\d]*[\\,][[\\s]*\\d\\,]*")
            || inputValue.matches("[\\w]*[\\,][[\\s]*\\w\\,]*") || inputValue.matches("[\\d]*[\\s]*[\\?]")
            || inputValue.matches("[\\w]*[\\s]*[\\?]") || inputValue.matches("[\\d]*[\\s]*[\\*]") || inputValue.matches("[\\w]*[\\s]*[\\*]")
            || inputValue.matches("[\\w]*[\\s]*[\\w\\,]*") || inputValue.matches("[\\s]*[\\%]*[\\s]*[\\w]*[\\s]*")
            || inputValue.matches("[\\s]*[\\w]*[\\s]*[\\%][\\s]*") || inputValue.matches("[\\s]*[\\%]*[\\s]*[\\w]*[\\s]*[\\%][\\s]*")
            || inputValue.matches("[\\w]*[\\s]*[-][\\s]*[\\w]*") || inputValue.matches("[\\w]*[\\s]*[.][\\s]*[\\w]*")
            || inputValue.matches("[\\w]*[\\s]*['][\\s]*[\\w]*") || inputValue.matches("[[\\w]*[\\s]*[\\w]*[\\s]*]*")) {
        return true;
    }
    return false;
}

我想匹配字符串“sec 30-31”,当我匹配它的返回 false inputValue.matches("[\\w]*[\\s]*[-][\\s]*[\\w]*") 时,它将返回 true。

任何人都可以帮助我。

谢谢

司坦苏

【问题讨论】:

  • 请给出一个清晰的示例输入和预期输出。
  • 哦,这是模棱两可的:[[\\s]*\\d\\,]。在 Java 正则表达式中,内括号被忽略。
  • 另外,您可以简单地使用if(a) { return true; } else { return false; },而不是return a;
  • @Sitansu:你需要所有这些正则表达式吗?我怀疑有人会为你“解码”它们。要匹配您预期的字符串,您只需要类似"[a-zA-Z]+\\s+\\d+-\\d+".
  • 仍不清楚。为什么是 30-31?它也应该匹配 80-81 吗?还有1-2?和99-00?前三个字母重要吗?字母的数量应该是 3 吗?由于目前写的问题,答案可能是:return inputValue.equals("sec 30-31");

标签: java regex pattern-matching


【解决方案1】:

你的正则表达式

inputValue.matches("[\\w]*[\\s]*[-][\\s]*[\\w]*")

不会匹配sec 30-31,因为它匹配alphanumerics+whitespaces+-+whitespaces+alphanumerics。如您所见,数字没有位置。

您需要在“管道”中添加另一个 matches()

inputValue.matches("[a-zA-Z]+\\s+\\d+-\\d+")

查看IDEONE demo 返回true

这里,

  • [a-zA-Z]+ - 匹配 1 个或多个拉丁字母
  • \\s+ - 匹配 1 个或多个空格
  • \\d+ - 匹配 1 个或多个数字
  • - - 匹配文字连字符
  • \\d+ - 匹配 1 个或多个数字。

【讨论】:

  • 很高兴它对你有用。如果我的回答对您有帮助,也请考虑投票。
猜你喜欢
  • 2015-08-31
  • 1970-01-01
  • 2021-05-13
  • 2021-10-03
  • 2011-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多