Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match path

Tags:

c#

regex

asp.net

I trying to validate user entered string is correct relative path or not.

  • It should not start with assets/
  • It should not end with /
  • It should not end with any file extension like .html or .php or .jpg
  • It should not contain dot .

I am trying with below regex, but it is not working correctly.

^([a-z]:)*(\/*(\.*[a-z0-9]+\/)*(\.*[a-z0-9]+))

My test cases

Valid path

  • sample/hello/images
  • sample/hello_vid/user/data
  • test/123/user_live/images

Invalid path

  • assets/sample/hello/images
  • sample/hello_vid/user/data/
  • test/123/user_live/images/index.html
  • hii/sk.123/data
  • ok/bye/last.exe
like image 641
Programmer Avatar asked Jan 01 '23 00:01

Programmer


2 Answers

Alternative "readable" approach ;)

public static bool IsValidPath(this string path)
{
    if (string.IsNullOrEmpty(path)) return false;
    if (path.StartsWith("assets/")) return false;
    if (path.EndsWith("/")) return false;
    if (path.Contains(".")) return false;

    return true;
}

// Usage
var value = "sample/hello/images";
if (value.IsValidPath())
{
    // use the value...
}
like image 90
Fabio Avatar answered Jan 05 '23 15:01

Fabio


If you also want to match the underscore, you could add it to the character class. To prevent matching assets/ at the start, you could use a negative lookahead.

^(?!assets/)[a-z0-9_]+(?:/[a-z0-9_]+)+$
  • ^ Start of string
  • (?!assets/) Assert what is directly to the right is not assets/
  • [a-z0-9_]+ Repeat 1+ times any of the listed, including the underscore
  • (?:/[a-z0-9_]+)+ Repeat 1+ times a / and 1+ times any of the listed
  • $ End of string

Regex demo

Or you could use \w instead of the character class

^(?!assets/)\w+(?:/\w+)+$
like image 45
The fourth bird Avatar answered Jan 05 '23 16:01

The fourth bird