You can try a backlink that matches the same text that was previously matched by the capture group.
- . (...), , \index_of_group
\d{3}([-.])\d{3}\1\d{4}
Captured Group 1----^^^^ ^^-------- Back Reference first matched group
-
:
System.out.print("123-456-7890".matches("^\\d{3}([-.])\\d{3}\\1\\d{4}$"));//true
System.out.print("123.456.7890".matches("^\\d{3}([-.])\\d{3}\\1\\d{4}$"));//true
System.out.print("123-456.7890".matches("^\\d{3}([-.])\\d{3}\\1\\d{4}$"));//false
:
\d{3} digits (0-9) (3 times)
( group and capture to \1:
[-.] any character of: '-', '.'
) end of \1
\d{3} digits (0-9) (3 times)
\1 what was matched by capture \1
\d{4} digits (0-9) (4 times)