How can I create a java regular expression for a comma separator list
(3)
(3,6)
(3 , 6 )
I tried, but it does not match anything:
Pattern.compile("\\(\\S[,]+\\)")
and how can I get the value “3” or “3”and “6” in my code from the Matcher class?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Validation regex
You can try this meta-regex approach for clarity:
The
partpattern is[^\s(,)]+, i.e. one or more of anything but whitespace, brackets and comma. This construct is called the negated character class.[aeiou]matches any of the 5 vowel letters;[^aeiou]matches everything but (which includes consonants but also numbers, symbols, whitespaces).The
+repetition is also made possessive to++for optimization. The(?:...)construct is a non-capturing group, also for optimization.References
java.util.regex.PatternTesting and splitting
We can then test the pattern as follows:
This prints:
This uses
String.splitto get aString[]of all the parts after trimming the brackets out.