3 回答

TA貢獻(xiàn)1796條經(jīng)驗(yàn) 獲得超10個(gè)贊
這是正則表達(dá)式:
^[^\d]*\d+[^\d]*$
這是零個(gè)或多個(gè)非數(shù)字,然后是數(shù)字的子字符串,然后又是零個(gè)或多個(gè)非數(shù)字,直到字符串結(jié)尾。這是Java代碼(帶有轉(zhuǎn)義的斜杠):
class MainClass {
public static void main(String[] args) {
String regex="^[^\\d]*\\d+[^\\d]*$";
System.out.println("1".matches(regex)); // true
System.out.println("XX-1234".matches(regex)); // true
System.out.println("XX-1234-YY".matches(regex)); // true
System.out.println("do-not-match-no-integers".matches(regex)); // false
System.out.println("do-not-match-1234-567".matches(regex)); // false
System.out.println("do-not-match-123-456".matches(regex)); // false
}
}

TA貢獻(xiàn)1852條經(jīng)驗(yàn) 獲得超7個(gè)贊
Matcher.find()會嘗試在字符串中找到匹配項(xiàng)。您應(yīng)該嘗試Matcher.matches()查看模式是否適合所有字符串。
這樣,您需要的模式是 \d+
編輯:似乎我誤解了這個(gè)問題。使用相同模式查找字符串是否只有一個(gè)整數(shù)的一種方法是:
int matchCounter = 0;
while (Matcher.find() || matchCounter < 2){
matchCounter++;
}
return matchCounter == 1

TA貢獻(xiàn)1872條經(jīng)驗(yàn) 獲得超4個(gè)贊
您可以使用RegEx ^\D*?(\d+)\D*?$
^\D*?
確保行首與第一組之間沒有數(shù)字(\d+)
匹配您的數(shù)字\D*?$
確保您的第一組和行尾之間沒有數(shù)字
因此,對于您的Java字符串,應(yīng)為: ^\\D*?(\\d+)\\D*?$
添加回答
舉報(bào)