Regex: allow only character if another character is found in string

Is it possible to exclude the use of certain characters if another character is already found?

For example, the telephone numbers 123-456-7890 and 123.456.7890 are valid in the field, but 123-456.7890 are not.

per minute when I have:

static String pattern = "\\d{3}[-.]\\d{3}[-.]\\d{4}";

How can this be improved to fulfill the above requirement?

To clarify, it will be used in the line that will be compiled for the Pattern object:

 Pattern p = Pattern.compile(pattern);

Then used in matches:

Matcher m = p.matcher(phoneNumber);
if(m.find()){
    //do stuff
}
+4
source share
1 answer

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)
+7

All Articles