Home > Software engineering >  Creating Regex for url path
Creating Regex for url path

Time:09-12

im very new to regex and have been trying to create an expression which creates validation for a path. Below are the rules I would like to include

  • MUST begin and end with forward slash e.g /example/
  • path name must be between 1-63 characters
  • no upper case characters allowed
  • no spaces
  • can only contain the following symbols "-", ".", "_", "~"

This is what I currently have ^((?/)[a-z0-9]{1,63}/)$

Can someone please tell me how to include the rules above?

Thankyou!

EDIT image showing error on regex101.com

enter image description here

CodePudding user response:

You can use

^/[a-z0-9._~-]{1,61}/$

Or, if you plan to add more specific parts to the pattern, a lookahead version will become handier:

^(?=.{1,63}$)/[a-z0-9._~-] /$

See the regex demo #1 and regex demo#2. Note that in the C# code, where you define regexes with regular or verbatim string literals, you do not need to escape slashes as they are not special regex chars.

Details:

  • ^ - start of string anchor
  • (?=.{1,63}$) - a positive lookahead that requires the string to contain one to 63 chars other than line break chars till the end of string
  • / - a / char
  • [a-z0-9._~-]{1,61} - one to 61 lowercase ASCII letters, digits, ., _, ~, or - chars
  • [a-z0-9._~-] - one or more lowercase ASCII letters, digits, ., _, ~, or - chars
  • / - a / char
  • $ - end of string.

CodePudding user response:

Try RegexPlus or dk.brics.automaton, as it allows &-operator so that you could write:

/(\w{1,63})&(http...)/

  • Related