问题描述
我做了一个正则表达式来检查String的长度,所有字符都是数字并以数字开头,例如123
以下是我的表达式
I made a regular expression for checking the length of String , all characters are numbers and start with number e.g 123Following is my expression
REGEX =^123\\d+{9}$";
但它无法检查String的长度。它验证那些字符串只有它们的长度是9并从123开始。
但是如果我传递字符串1234567891它也验证它。但是我应该怎么做呢在我这边是错的。
But it was unable to check the length of String. It validates those strings only their length is 9 and start with 123.But if I pass the String 1234567891 it also validates it. But how should I do it which thing is wrong on my side.
推荐答案
就像这里已经回答的那样,最简单的方法就是删除 +
:
Like already answered here, the simplest way is just removing the +
:
^123\\d{9}$
或
^123\\d{6}$
具体取决于您的需求。
你也可以使用另一种,更复杂和通用的方法,消极前瞻:
You can also use another, a bit more complicated and generic approach, a negative lookahead:
(?!.{10,})^123\\d+$
说明:
这: (?!。{10,})
是负面预测(?=
会是一个积极的表情-ahead),这意味着如果前瞻后的表达式匹配此模式,则整个字符串不匹配。大致意味着:仅当负前瞻中的模式与不匹配时,才会满足此正则表达式的条件。
This: (?!.{10,})
is a negative look-ahead (?=
would be a positive look-ahead), it means that if the expression after the look-ahead matches this pattern, then the overall string doesn't match. Roughly it means: The criteria for this regular expression is only met if the pattern in the negative look-ahead doesn't match.
In在这种情况下,字符串匹配仅如果。{10}
不匹配,这意味着10个或更多字符,所以它只匹配前面的模式最多匹配9个字符。
In this case, the string matches only if .{10}
doesn't match, which means 10 or more characters, so it only matches if the pattern in front matches up to 9 characters.
正向前瞻相反,只有在前瞻中的条件匹配。
A positive look-ahead does the opposite, only matching if the criteria in the look-ahead also matches.
出于好奇的缘故,将它放在这里,它比你需要的更复杂。
Just putting this here for curiosity sake, it's more complex than what you need for this.
这篇关于String的Java Regex以数字和固定长度开头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!