Java regex to check if string is valid number format (comma and decimal point placing)

五迷三道 提交于 2021-01-01 08:56:14

问题


1000 - valid
1,000 - valid
1,000.00 - valid
1000.00 - valid
1000.00.00 - invalid
1,0.00 - invalid
1,000,00.00 - invalid
1,000,000.12 - valid

no of decimal places can be unlimited

I've been trying to find the right regex pattern, can't seem to find one that will accomodate all validations. Can anyone help

the pattern ^[1-9]\d{0,2}(.\d{3})*(,\d+)?$ did not work for me, based from the similar thread here


回答1:


You should try this expression:

^\d{1,3}|\d(([ ,]?\d{3})*([.,]\d{2}+)?$)

With this expression is covered with the scenarios raised.

Here the complete example:

public class Decimal {

    private static String REGEX = "^\\d{1,3}|\\d(([ ,]?\\d{3})*([.,]\\d{2}+)?$)";

    public static void main(String[] args) {
        String data[] = {"1000", "1,000", "1,000.00", "1000.00", "1000.00.00", "1,0.00", "1,000,00.00", "1,000,000.12"};

        Pattern.compile(REGEX);

        for (int i = 0; i < data.length; i++) {
            if (data[i].matches(REGEX)) {
                System.out.println(data[i] + " - valid");
            } else {
                System.out.println(data[i] + " - invalid");
            }
        }
    }

}

The output:

  • 1000 - valid
  • 1,000 - valid
  • 1,000.00 - valid
  • 1000.00 - valid
  • 1000.00.00 - invalid
  • 1,0.00 - invalid
  • 1,000,00.00 - invalid
  • 1,000,000.12 - valid



回答2:


This is one of possible regexes you are looking for:

^\d{1,3}([ ,]?\d{3})*([.,]\d+)?$

Demo: https://regex101.com/r/T8tcDP/1




回答3:


This would match your numbers there (?:\d+(?:,\d{3})*(?:\.\d{2})?|\.\d{2})
It would also match .00 just incase. If you don't want it to, just remove
the |\.\d{2} part.

Add your own boundary constructs as needed ^$ or \b

Expanded

 (?:
      \d+ 
      (?: , \d{3} )*
      (?: \. \d{2} )?
   |  \. \d{2} 
 )



回答4:


My suggestion is:

^[1-9]((\d{0,2}(,\d{3})*(\.(\d{3},)*\d{1,3})?)|(\d*(\.\d+)?))$

A number either has separators for every 3 digits or it hasn’t (no middle forms). It either has a decimal point and at least one digit after it, or it hasn’t. In all cases does it start with a non-zero digit.

Remember that a dot (period, .) has a special meaning in regex and therefore needs to be escaped to get a literal point.



来源:https://stackoverflow.com/questions/42822629/java-regex-to-check-if-string-is-valid-number-format-comma-and-decimal-point-pl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!