0

I have a simple regex ^\\{2}[a-z0-9?_?]*\\{1}[a-z0-9?_?]*$ that can validate folder paths of the type \\foo_bar1\foo_bar_2.

The problem is that the complete path is created by the user using a form and it is unknown how deep the user might want to nest directories. Regardless, I want to make sure that the path is validated, for example, the user might want to create a path like \\foo_bar1\foo_bar_2\foo_bar_3\foo_bar_4\foo_bar_n.

Is there a way I can generalize the \\{1}[a-z0-9?_?]* part of the regex for the above problem for n number of nested directories?

4
  • What did you try to achieve with ?_?? Looking at your example I guess ^\\\\\w+(?:\\\w+)*$ will work. Commented Aug 23, 2021 at 6:24
  • ?_? numbers and underscores can be optional in the folder path, however no other special characters Commented Aug 23, 2021 at 6:26
  • Then the given regex would work I guess since \w is shorthand for [A-Za-z0-9_]. Commented Aug 23, 2021 at 6:28
  • 1
    @JvdV yes, just tested, it works perfectly, what is ?: doing though? also, if you feel like it, could you please write a short answer and I can accept it :) thanks Commented Aug 23, 2021 at 6:34

1 Answer 1

1

If you are looking to find a pattern that would accept alphanumeric characters and underscores, you could simply make use of the \w+ shorthand to match any word-character:

^\\\\\w+(?:\\\w+)*$

See an online demo:

  • ^ - Start-line anchor.
  • \\\\ - Two escaped (therefor literal) backslash characters.
  • \w+ - 1+ Word-characters.
  • (?: - Open a non-capture group:
    • \\\w+ - A single literal backslash (\\) followed by 1+ word-characters (\w+).
    • )* - Close non-capture group and match it 0+ times.
Sign up to request clarification or add additional context in comments.

Comments

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.