RegEx to match X digits with one extra comma between digits?

I am trying to write RegExp to match only 8 digits, with one extra comma being hidden between the digits.

All must comply with:

12345678
12,45678
123456,8

Now I have:

^[0-9,]{8}

but of course mistakenly matches 012,,,67

Example: https://regex101.com/r/dX9aS9/1

I know that there are options, but I don’t understand how to keep the 8-bit length applied to the comma, and also keep the comma limited to 1.

Any advice would be appreciated, thanks!

+4
source share
3 answers

To match string 8 char, which can only contain numbers and an optional comma between them, you can use

^(?=.{8}$)\d+,?\d+$

regex

, 8 . ,? , + \d 1 .

8 ,

^(?:(?=.{9}$)\d+,\d+|\d{8})$

regex

, 9 ( ) 8 - .

:

  • ^ -
  • (?:(?=.{9}$)\d+,\d+|\d{8}) - 2 :
    • (?=.{9}$)\d+,\d+ - 1 + , 1 , 1 + , 9 char long (8 1 )
    • | -
    • \d{8} - 8
  • $ -

Java code demo ( , String#matches(), ^ $ , ):

List<String> strs = Arrays.asList("0123,,678", "0123456", // bad
        "01234,567", "01234567" // good
    );
for (String str : strs)
    System.out.println(str.matches("(?:(?=.{9}$)\\d+,\\d+|\\d{8})"));

/:

+ ( 1 ) * ( 0 ) , :

^(?:(?=.{9}$)\d*,\d*|\d{8})$

- regex

+2

, :

^((\d,?){8})$

:

^((\d,?){8})(?<!,)$

(?<!,) - .

+1

/^(?!\d{0,6},\d{0,6},\d{0,6})(?=\d[\d,]{6}\d).{8}$/

, , . g, 8 .

http://regexr.com/3d63m

: (?!\d{0,6},\d{0,6},\d{0,6}) , 6 , (?=\d[\d,]{6}\d) 6 . .{8} 8 .

+1

All Articles