user1978406
user1978406

Reputation: 65

Allow any digit in a string other than 9 and 16 digits

^(?![\\s\\S]*(\\d{16})|[\\s\\S]*(\\d{9}))[\\s\\S]*

The above regex does not allow a number greater than 10 digits in the string. Example, if user enters test 1234567891. The text is a valid text. We should allow user to enter this text. The user should only not enter a 9 digit number or a 16 digit number. Example, test 123456789 should be invalid. How to modify the regex.

Upvotes: 2

Views: 177

Answers (2)

fge
fge

Reputation: 121712

Don't use a regex for this kind of check. Java has .length() on strings:

private static final Pattern DIGITS = "\\d+";

public boolean inputOK(String input)
{
    Matcher m = DIGITS.matcher(input);

    int len;

    while (m.find()) {
        len = m.group().length();
        if (len == 9 || len == 16)
            return false;
    }

    return true;
}

Upvotes: 1

Brian Agnew
Brian Agnew

Reputation: 272247

Is this requirement best served by a regexp ? I think it would be much more readable to check the string length, and if you have a number.

Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems.

and see here.

Upvotes: 6

Related Questions