不使用单个正则表达式来解决这个特定问题会容易得多。
首先,\b
是零宽度。所以你不需要跟随它使用 a ?
,你的意图可能是\s?
。
接下来,在一般情况下,正则表达式几乎是无状态的,这意味着您需要按如下方式构建正则表达式。
^\s*(one\s*,(two\s*,(three\s*,four|four\s*,three)|three\s*,(two\s*,four|four\s*,two)...
如您所见,您必须手动处理组合爆炸。这远远不够理想。
相反,您应该拆分,
并使用 java 进行检查。
感谢回复。据我了解,您希望我不使用正则表达式,而是使用 java。您能否详细介绍一下如何签入 java
试试这个(未经测试的代码,将是错误):
public parseList(String input) {
String[] numbers = { "one", "two", "three", "four" };
bool foundNumbers = { false, false, false, false };
String delims = "\s*,";
String[] tokens = input.split(delims);
if (tokens.length != 4) {
//deal with error case as you wish
}
for (int i = 0; i < numbers.length; ++i) {
for (int j = 0; j < tokens.length; ++j) {
if (numbers[i].equals(tokens[j])) {
if (!foundNumbers[i]) {
foundNumbers[i] = true;
} else {
//deal with error case as you wish
}
}
}
}
for (int i = 0; i < foundNumbers.length; ++i) {
if (!foundNumbers[i]) {
//deal with error case as you wish
}
}
//success
}