Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex: Only allow a character if another character has been found in a string

Tags:

java

regex

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

For example, in a phone number field 123-456-7890 and 123.456.7890 are valid, but 123-456.7890 is not.

at the minute 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 a string, which will be compiled to a Pattern object:

 Pattern p = Pattern.compile(pattern);

Then used in a Matcher:

Matcher m = p.matcher(phoneNumber);
if(m.find()){
    //do stuff
}
like image 263
jbailie1991 Avatar asked Mar 19 '23 18:03

jbailie1991


1 Answers

You can try with back reference that matches the same text as previously matched by a capturing group.

You need to add - and . in a capturing group using (...) that can be referred in next match using \index_of_group

              \d{3}([-.])\d{3}\1\d{4}
Captured Group 1----^^^^      ^^-------- Back Reference first matched group

Here is online demo

Sample code:

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

Pattern explanation:

  \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)
like image 118
Braj Avatar answered Apr 26 '23 15:04

Braj