开发者

regex count in single match

I want to check if string doesn't have more than 5 numbers. I can do it this way:

Matcher matcher = Pattern.compile("\\d").ma开发者_运维问答tcher(val);
i = 0;
while (matcher.find()) {
    i++;
}

However I would like to do it without while (because we are using regex validation framework). I want to be able to match strings like

A2sad..3f,3,sdasad2..2


This regex matches strings containing a max of 5 digits:

^(\D*\d){0,5}\D*$

And if you want to match strings consisting of exactly 5 digits, do:

^(\D*\d){5}\D*$

Note that inside a java.lang.String literal, you'll need to escape the backslashes:

boolean match = "A2sad..3f,3,sdasad2..2".matches("(\\D*\\d){0,5}\\D*");

or:

boolean match = "A2sad..3f,3,sdasad2..2".matches("(\\D*\\d){5}\\D*");

and you don't need to add the "anchors" ^ and $ since Java's matches(...) already does a full match of the string.


Try this regular expression:

^\D*(?:\d\D*){0,5}$

\d is a single digit and \D is the complement to that, so any character except a digit. (?:…) is like a normal grouping except its submatch cannot be referenced.

This regular expression allows any non-digit characters at the start, followed by at most five sequences of a single digit followed by optional non-digit characters.


One way is to use negative look-ahead:

^(?!(?:\D*\d){6})
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜