rz3r0 rz3r0 - 2 years ago 133
Java Question

PatternSyntaxException unclosed group

I have this RegEx String..

String regex = ^(/|\\){2}(projects|depot|perforce_[0-9a-zA-Z]+)(\\1)q(uality|a)]+)(\\1)$

String test cases that should match with this regex:

  1. //depot/quality/

  2. \\projects\qa\

  3. //perforce_0tests001/quality/

Explanation for this regex:

  1. match beginning

  2. group1: / or \ (only two times)

  3. group2: depot or projects or perforce_xn where xn is any digit or letter

  4. group3: references group1 only once

  5. q

  6. group4: uality or a

  7. group5: references group1 only once

  8. match end

This regex is failing with the following exception with string //depot/quality/

java.util.regex.PatternSyntaxException: Unclosed group near index 64

My other problem is that I want to also allow in group1 the vertical bar character: |

So that the following string also matches: ||depot|quality|

How can I do that? I don't know how to escape it?

Answer Source
String regex = "^(\\/|\\\\|\\|){2}(projects|depot|perforce_[0-9a-zA-Z]+)(\\1)q(uality|a)(\\1)$";

This Java regex String should work fine for you. As you can see \\| will be parsed in Java to \| which is a regex escape for the vertical bar.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download