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
}
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With