[英]Java - Regular Expression to check if the string contains continuous digit along with other characters
我正在尋找編寫正則表達式來檢查字符串是否包含以下內容:
例如:
您可以使用此正則表達式:
^\D*(?:\d{2,5}|\d{9,})\D*$
簡短說明(您也可以訪問演示查看說明):
^
: 開始錨點\D*
: 任意數量的非數字(?:
: 非捕獲組的開始\d{2,5}
: 2-5 位數字|
: 交流發電機\d{9,}
: 9 位或更多位)
: 非捕獲組結束\D*
: 任意數量的非數字$
: 結束錨點如果您使用任何一種方法:
String.matches()
Pattern.matches()
Matcher.matches()
然后你不必指定開始和結束錨點, ^
和$
Pattern pattern =
Pattern.compile("(?<!\\d)(\\d{2,5})(?!\\d)|\\d{9,}");
Matcher matcher =
pattern.matcher("111lo, I stay at 100 Feet R10034"); // your input here
while (matcher.find()) {
System.out.format("I found the text" +
" \"%s\" starting at " +
"index %d and ending at index %d.%n",
matcher.group(),
matcher.start(),
matcher.end());
}
簡短說明:
(?<!\\d)
: 與非數字字符匹配的負向回溯\\d{2,5}
:長度為 2 到 5 的數字(?!\\d)
:與非數字字符匹配的負前瞻|
: 交替\\d{9,}
:匹配長度為 9 或更多的數字你可以做這樣的事情。
fun checkDigit(inputValue: String): Boolean {
var isContinueDigit = false
var digitSize = 0
inputValue.forEach {
if (it.isDigit()) {
if (isContinueDigit) {
digitSize++
} else {
isContinueDigit = true
digitSize = 0
digitSize++
}
} else {
isContinueDigit = false
}
}
val isDigit: ArrayList<Int> = arrayListOf(2, 3, 4, 5, 9)
return isDigit.contains(digitSize) || isDigit.last() < digitSize
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.