[英]Java - Regular Expression to check if the string contains continuous digit along with other characters
I am looking to write regular expressions to check if a string contains below:我正在寻找编写正则表达式来检查字符串是否包含以下内容:
For example:例如:
You can use this regex:您可以使用此正则表达式:
^\D*(?:\d{2,5}|\d{9,})\D*$
Short explanation (You can also visit the demo to see an explanation):简短说明(您也可以访问演示查看说明):
^
: Start anchor ^
: 开始锚点\D*
: Any amount of non digits \D*
: 任意数量的非数字(?:
: Start of a non capture group (?:
: 非捕获组的开始\d{2,5}
: 2-5 digit s \d{2,5}
: 2-5 位数字|
: Alternator \d{9,}
: 9 or more digits \d{9,}
: 9 位或更多位)
: End of non capture group )
: 非捕获组结束\D*
: Any amount of non digits \D*
: 任意数量的非数字$
: End anchor $
: 结束锚点If you use any of the methods:如果您使用任何一种方法:
String.matches()
Pattern.matches()
Matcher.matches()
Then you don't have to specify the start and end anchor, ^
and $
然后你不必指定开始和结束锚点,
^
和$
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());
}
Short explanation:简短说明:
(?<!\\d)
: negative lookbehind that matches with character that isn't a digit (?<!\\d)
: 与非数字字符匹配的负向回溯\\d{2,5}
: digits of length 2 to 5 \\d{2,5}
:长度为 2 到 5 的数字(?!\\d)
: negative lookahead that matches with character that isn't a digit (?!\\d)
:与非数字字符匹配的负前瞻|
: alternation \\d{9,}
: matches digits of length 9 or more \\d{9,}
:匹配长度为 9 或更多的数字You can do something like that.你可以做这样的事情。
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.