Home > OS >  Why can't I make a group repeat in regex Java?
Why can't I make a group repeat in regex Java?

Time:10-29

I have a regex I want to construct for validating the UNC syntax, which is:

\\server\shared\folder\path

I don't care about the server or folder characters, I exclusively want to validate the \thing1\thing2maybe3 syntax, the server and folder names will be validated separately.

This is what I have so far:

(^\\\\\w )(\\{1}\w ) (. (?<!\\)$)

These are my tests:

  1. MATCH - \\server\multiple\folders\example\path
  2. FAIL - \\server\\multiple\folders\example\path
  3. SHOULD FAIL - \\server\multiple\\folders\example\path
  4. FAIL - \\server\multiplefolders\example\path\
  5. FAIL - \\server
  6. FAIL - \\\server\multiple
  7. SHOULD MATCH - \\server\m
  8. MATCH - \\server\m\w\z

I'm testing here: https://regex101.com/r/WqF7h7/1

Can anyone help making #3 and #7 fail and match respectively?

#3 has a second double slash after "multiple", this shouldn't be permitted, only at the beginning should there be double slashes. This should fail like #2

#7 has the correct syntax and should be matching like #8

Thanks.

CodePudding user response:

You can use

^\\{1,2}\w (?:\\\w ) $

In Java with the doubled backslashes:

String regex = "^\\\\{1,2}\\w (?:\\\\\\w ) $";

The pattern matches:

  • ^ Start of string
  • \\{1,2} Match 1 or 2 backslashes
  • \w Match 1 word characters
  • (?:\\\w ) Repeat 1 times 1 or more word characters
  • $ End of string

Regex demo

Or a bit less strict version matching any char except \ instead of only word characters:

^\\{1,2}[^\\] (?:\\[^\\] ) $
  • Related