简体   繁体   中英

How can I modify my regular expression to test only the characters in a string that appear before alphanumeric characters appear?

I'm trying to test a string that is a file path with a regular expression, and I want the test of the regex to return true if and only if the characters before the file name (which are alphanumeric characters only) are ./ or ./../ . My issue is that if the path contains a directory such as ./../../ , the test returns true because the directory begins with ./ .

I figure that if I test for an exact match on only the characters that appear before any alphanumeric characters, I can eliminate this problem, but I don't know how to do this.

Code:

function validPath(path) {
   if (!/^(\.\/|\.\/\.\.\/)/.test(path)) {
      path = "ERROR" //the path is not valid if ERROR is returned
   }

   return path;      //the path is valid if the path is returned
}

I expect the output of validPath('./../../index.html') to be ERROR , but the output is ./../../index.html

If you know that all file names begin with ascii letters or digits or underscores you can extend your regex to say that the next character after the ./ or ./../ must be one of the leading characters of a file name:

if (!/^(\.\/|\.\/\.\.\/)\w/.test(path)) {

Here \\w stands for [A-Za-z0-9_] .

If you wish to accept filenames that begin with a dot or non-ASCII letters, you'll have more work to do.

JavaScript regexes do not natively handle non-ASCII letters, but you can get a third party regex engine to do so.

Another approach is to say

if (!/^(\.\/|\.\/\.\.\/)[^.]/.test(path)) {

which means you don't want the first character after the ./ or ./../ to be another dot. This will handle filenames with non-ASCII letters, but it won't pick up hidden files that begin with a dot.

Hope that gets you closer!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM