[英]Java regex - allow only if n digits in group from long string
我需要一個允許字符串的正則表達式,除非在任何一個組中有6個或更多的數字。
我目前錯誤的正則表達式:
^([a-zA-Z ]*)|(\d{0,5})$
比賽:
teststring 12345
teststring
1234 teststring
teststring 123 teststring
test1234string
不匹配:
1234567 teststring
teststring 123456
test123456789string
我希望有人能幫幫忙。 大家好
更新:這個正則表達式做的工作:
^(?!.*\d{6}).*$
thx @WiktorStribiżew
匹配沒有6個連續數字的字符串的模式是
^(?!.*\d{6}).*
正則表達式演示可在此處獲得 。 如果里面有換行符,你需要添加一個DOTALL修飾符.
匹配所有字符,包括換行符:( (?s)^(?!.*\\d{6}).*
。
細節
^
- 字符串的開頭(在matches()
隱含) (?!.*\\d{6})
- 如果有盡可能多的0個字符后跟6個連續數字,則表示匹配失敗的負向前瞻 .*
- 盡可能多的0個字符 在Java中,您可以通過以下方式使用它:
Boolean found = s.matches("(?s)(?!.*\\d{6}).*");
請注意,您可能只是嘗試使用Matcher#find
#find找到6位數字,如果找不到,請繼續執行代碼:
if (!Pattern.compile("\\d{6}").matcher(s).find()) {
// Cool, proceed
}
您可以替換匹配\\d{6,}
第一個組\\d{6,}
然后檢查原始長度的結果長度:
String text = "1234567 teststring";
boolean check = text.replaceFirst("\\d{6,}", "").length() == text.length();
那個正則表達式怎么樣:
^(\D*)\d{0,5}(\D*)$
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.