2

I'm trying to create a regex pattern to match a specific string and return true if the string matches the pattern and false if it doesn't. Here are the conditions:

  1. Must start with [ and end with ]
  2. Each item inside the brackets have to be separated by commas
  3. Each item separated by commas have to follow this regex pattern: ^[A-Za-z][A-Za-z0-9_]*$

How can I make one regex that checks for all these conditions?

1
  • No whitespace allowed anywhere? Commented Jul 4, 2016 at 18:21

2 Answers 2

3

Enclose in the group which could repeat:

\[[A-Za-z][A-Za-z0-9_]*(?:,[A-Za-z][A-Za-z0-9_])*\]

This is as it should appear in the final string. Escape specials according to specific language.

Sign up to request clarification or add additional context in comments.

1 Comment

It is better for regex performance to make the second half repeating (reduces backtracking), and there's no need to capture anything, so: \[[A-Za-z][A-Za-z0-9_]*(?:,[A-Za-z][A-Za-z0-9_]*)*\]
2

In Java, \w without the Pattern.UNICODE_CHARACTER_CLASS flag actually matches the same as [a-zA-Z0-9_]. So, I'd use

String pat = "\\[[a-zA-Z]\\w*(?:,[a-zA-Z]\\w*)*]";

See the IDEONE demo. Use with String#matches, or you will have to add ^ (or \\A) at the beginning and $ (or \\z) at the end.

String pat = "\\[[a-zA-Z]\\w*(?:,[a-zA-Z]\\w*)*]";
System.out.println("[c1,T4,yu5]".matches(pat)); // TRUE

Pattern explanation:

  • \\[ - a literal [
  • [a-zA-Z] - an English letter (same as \\p{Alpha})
  • \\w* - zero or more characters from [a-zA-Z0-9_] set
  • (?: - start of the non-capturing group matching...
    • , - a comma
    • [a-zA-Z]\\w* - see above
  • )* - ... zero or more times
  • ] - a literal ] (does not require escaping outside of the character class to be treated literally).

2 Comments

So this is essentially the same regex as Zbynek's except you replaced [a-zA-Z0-9_] with \\w?
If it is, then both work for me. Thank you for the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.