【发布时间】: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