Search code examples
javascriptregex

RegEx to find string representing local paths


I'm trying to find all strings which are local paths like:

@/path/to
@@/path/to
./path/to
../path/to
../../path/to

And at the same time ignore all string, which could be a module like

@next/module

Therefore I use this regexp:

^[.\/|~\/|@\/|@@\/]

But this also matches the module, which I don't want to. I thought I have to search for a starting DOT or AT followed by a SLASH should work...

RegEx


Solution

  • You might use:

    ^(?:@@?|\.\.?)\/\S+
    

    The pattern matches:

    • ^ Start of string
    • (?:@@?|\.\.?) Match either @ @@ . ..
    • \/\S+ Match / followed by 1+ non whitspace characters

    Regex demo

    Or allowing 1 or 2 @ chars at the start or optional repetitions of 1 or 2 dots followed by / and matching only word characters:

    ^(?:@@?\/|(?:\.\.?\/)+)\w+(?:\/\w+)*
    

    Regex demo