0

Need regular expression for format where maximum 7 digits are allowed, with comma after every third digit.

Valid values are:

7
 77
 555
 1,234
12,345
444,888
4,669,988

Currently I am using ([0-9]{1}(,?[0-9]{3}){1,2} which fails in first three scenarios.

2
  • 1
    Do you have to use a regex for it? DecimalFormat would be a much more straight forward choice. Commented Jul 18, 2013 at 9:52
  • Parse the number and make sure it is less than 10^8. Commented Jul 18, 2013 at 9:53

3 Answers 3

2

Use this one:

[0-9]{1,3}(,[0-9]{3}){0,2}

To validate an integer from string (you have to remove ,):

try {
  Integer.parseInt(str.replaceAll(",","");
  //valid integer
} catch (Exception e) {
  //not valid integer
}
Sign up to request clarification or add additional context in comments.

2 Comments

It also accepts "111,123,446" and "11,123,446".But limit is 7.
I need to validate with comma to check proper comma position and limit characters max length to 7.
2

try this regex

"\\d{1,3}|\\d{1,3},\\d{3}|\\d{1,2},\\d{3},\\d{3}"

Comments

0
\d{1,3}(,\d{3}){0,2}

Try this regex along with number validation for a length check.

public boolean isNumValid(String num) throws ParseException {
    if (!(NumberFormat.getInstance().parse(num).intValue() > 9999999)) {
        if (num.matches("\\d{1,3}(,\\d{3}){0,2}")) {
            return true;
        }
    }
    return false;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.