團隊, 我有一個任務。即,我想要在數據的blcvk中檢查98%
。 我想寫一些正則表達式,但它給連續的錯誤。Java String RegularExpressions
String str="OAM-2 OMFUL abmasc01 and prdrot01 98% users NB in host nus918pe locked.";
if(str.matches("[0-9][0-9]%"))
但它返回false。
迴應是真正的讚賞。
團隊, 我有一個任務。即,我想要在數據的blcvk中檢查98%
。 我想寫一些正則表達式,但它給連續的錯誤。Java String RegularExpressions
String str="OAM-2 OMFUL abmasc01 and prdrot01 98% users NB in host nus918pe locked.";
if(str.matches("[0-9][0-9]%"))
但它返回false。
迴應是真正的讚賞。
使用模式/匹配器/查找方法。 matches
將正則表達式應用於整個字符串。
Pattern pattern = Pattern.compile("[0-9]{2}%");
String test = "OAM-2 OMFUL abmasc01 and prdrot01 98% users NB in host nus918pe locked.";
Matcher matcher = pattern.matcher(test);
if(matcher.find()) {
System.out.println("Matched!");
}
嘗試:
str.matches(".*[0-9][0-9]%.*")
或(\d
=數字):
str.matches(".*\\d\\d%.*")
匹配模式也應該與來之前的字符/在98%
後,這就是爲什麼你應該加上.*
評論:
您可以使用模式匹配像其他人則建議,如果要提取98%
出字符串它是特別有效的 - 但如果你只是希望找到,如果有一個匹配 - 我發現.matches()
是使用更簡單。
你可以嘗試這個正則表達式\d{1,2}(\.\d{0,2})?%
這將匹配98%
或百分比與十進制值,如98.56%
以及。
Pattern pattern = Pattern.compile("\\d{1,2}(\\.\\d{0,2})?%");
String yourString= "OAM-2 OMFUL abmasc01 and prdrot01 98% users NB in host nus918pe locked.";
Matcher matcher = pattern.matcher(yourString);
while(matcher.find()) {
System.out.println(matcher.group());
}
str.matches("[0-9][0-9]%")
實際應用這個表達式^[0-9][0-9]%$
,這是在開始和結束錨定。其他人已經描述瞭解決方案。
完成了,謝謝你所有的回覆。 – user1835935
@ user1835935歡迎來到Stackoverflow!如果答案有幫助,您應該選擇其中一個,並通過點擊問題左上角的V(檢查標記)來「接受」它。你應該和你發佈的其他問題一樣。如果您發現有多個答案有幫助(您只能接受一個答案),您可以通過點擊「向上箭頭」來獲得其他有用的答案。 – alfasin