2 回答

TA贡献1880条经验 获得超4个赞
你可以很容易做到
boolean couldMatch(CharSequence charsSoFar, Pattern pattern) {
Matcher m = pattern.matcher(charsSoFar);
return m.matches() || m.hitEnd();
}
如果序列不匹配并且引擎没有到达输入的末尾,则意味着在末尾之前存在一个矛盾的字符,在末尾添加更多字符时该字符不会消失。
或者,正如文档所说:
如果在此匹配器执行的最后一次匹配操作中搜索引擎命中了输入的结尾,则返回 true。
当此方法返回 true 时,更多输入可能会更改上次搜索的结果。
这也在Scanner类内部使用,以确定它是否应该从源流加载更多数据以进行匹配操作。
将上述方法与您的样本数据一起使用会产生
Pattern fpNumber = Pattern.compile("[+-]?\\d*\\.?\\d*");
String[] positive = {"+", "-", "123", ".24", "-1.04" };
String[] negative = { "+A", "-B", "123z", ".24.", "-1.04+" };
for(String p: positive) {
System.out.println("should accept more input: "+p
+", couldMatch: "+couldMatch(p, fpNumber));
}
for(String n: negative) {
System.out.println("can never match at all: "+n
+", couldMatch: "+couldMatch(n, fpNumber));
}
should accept more input: +, couldMatch: true
should accept more input: -, couldMatch: true
should accept more input: 123, couldMatch: true
should accept more input: .24, couldMatch: true
should accept more input: -1.04, couldMatch: true
can never match at all: +A, couldMatch: false
can never match at all: -B, couldMatch: false
can never match at all: 123z, couldMatch: false
can never match at all: .24., couldMatch: false
can never match at all: -1.04+, couldMatch: false
当然,这并没有说明将不匹配的内容变成匹配的可能性。您仍然可以构建没有其他字符可以匹配的模式。但是,对于浮点数格式这样的普通用例,这是合理的。

TA贡献1824条经验 获得超5个赞
我没有具体的解决方案,但你可以用否定来做到这一点。
如果您在黑名单中设置了与您的模式绝对不匹配的正则表达式模式(例如 + 后跟字符),您可以对照这些进行检查。如果列入黑名单的正则表达式返回 true,则可以中止。
另一个想法是使用负前瞻(https://www.regular-expressions.info/lookaround.html)
添加回答
举报