2 回答

TA貢獻1880條經(jīng)驗 獲得超4個贊
你可以很容易做到
boolean couldMatch(CharSequence charsSoFar, Pattern pattern) {
Matcher m = pattern.matcher(charsSoFar);
return m.matches() || m.hitEnd();
}
如果序列不匹配并且引擎沒有到達輸入的末尾,則意味著在末尾之前存在一個矛盾的字符,在末尾添加更多字符時該字符不會消失。
或者,正如文檔所說:
如果在此匹配器執(zhí)行的最后一次匹配操作中搜索引擎命中了輸入的結(jié)尾,則返回 true。
當此方法返回 true 時,更多輸入可能會更改上次搜索的結(jié)果。
這也在Scanner類內(nèi)部使用,以確定它是否應該從源流加載更多數(shù)據(jù)以進行匹配操作。
將上述方法與您的樣本數(shù)據(jù)一起使用會產(chǎn)生
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
當然,這并沒有說明將不匹配的內(nèi)容變成匹配的可能性。您仍然可以構(gòu)建沒有其他字符可以匹配的模式。但是,對于浮點數(shù)格式這樣的普通用例,這是合理的。

TA貢獻1824條經(jīng)驗 獲得超5個贊
我沒有具體的解決方案,但你可以用否定來做到這一點。
如果您在黑名單中設(shè)置了與您的模式絕對不匹配的正則表達式模式(例如 + 后跟字符),您可以對照這些進行檢查。如果列入黑名單的正則表達式返回 true,則可以中止。
另一個想法是使用負前瞻(https://www.regular-expressions.info/lookaround.html)
添加回答
舉報