Skip to content
Advertisement

Why can’t I make a group repeat in regex Java?

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

\serversharedfolderpath

I don’t care about the server or folder characters, I exclusively want to validate the thing1thing2maybe3 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 – \servermultiplefoldersexamplepath
  2. FAIL – \server\multiplefoldersexamplepath
  3. SHOULD FAIL – \servermultiple\foldersexamplepath
  4. FAIL – \servermultiplefoldersexamplepath
  5. FAIL – \server
  6. FAIL – \servermultiple
  7. SHOULD MATCH – \serverm
  8. MATCH – \servermwz

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.

Advertisement

Answer

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}[^\]+(?:\[^\]+)+$
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement