Reputation: 35
I want check the format of a String. The formats possible are :
-"AZERTY"
-"AZERTY,REGULAR,AKILO"
I make this but I'm not sure :
String formatAttributes = "^[a-zA-Z0-9](,[a-zA-Z0-9])?*$";
It's correct ?
Upvotes: 2
Views: 187
Reputation: 15010
There are several plausible solutions here. Assuming that you only want to match exactly your two examples AZERTY
and AZERTY,REGULAR,AKILO
where the characters can be any a-z
.
^([a-z0-9]+(?:,[a-z0-9]+,[a-z0-9]+)?)$
Note: this expression assumes the use of the case insensitive flag.
Live Demo
https://regex101.com/r/yP6lX6/1
Upvotes: 0
Reputation: 45005
Here is how to proceed:
Pattern pattern = Pattern.compile("\\w+(,\\w+)*");
System.out.println(pattern.matcher("AZERTY").matches());
System.out.println(pattern.matcher("AZERTY,REGULAR,AKILO").matches());
Output:
true
true
NB: \w
is a word character: [a-zA-Z_0-9] which means that underscore has been added to your initial regular expression, if you don't want it, the regexp will be [a-zA-Z0-9]+(,[a-zA-Z0-9]+)*
Upvotes: 2