2

我必须验证以下格式的本地文件夹路径: ..\sentinel\log 。

我有 C:\sentinel\log 的旧正则表达式 ( /[\w]:\.*/)) 并且有效。我需要接受这条路。

我从 regexplibrary得到以下表达式

var pathRE = new RegExp("/^((../|[a-zA-Z0-9_/-\])*.[a-zA-Z0-9])"); 错误:语法错误:未终止的括号

当我执行时抛出此错误

我附上了我尝试过的代码

function checkFolderpath(path) {
    try {
        //var pathRE = new RegExp(/[\w]:\\.*/);
        var pathRE = new RegExp("/^((\.\./|[a-zA-Z0-9_/\-\\])*\.[a-zA-Z0-9])");
        if (pathRE.test(path)) {
            $("#spanloggererror").html("");
            return true;
        }
        else {
            $("#spanloggererror").html(resx_Invalid_Loggerpath);
            valtemp = 1;
        }
        return false;
    }
    catch (err) {
        alert(err.Message);
    }

请建议我如何解决这个问题。

编辑 :

路径值:..\Sentinel\log

4

2 回答 2

6

Your regular expression should be constructed like this:

var pathRE = /^((..\/|[a-zA-Z0-9_/-\\])*.[a-zA-Z0-9])/;

The only time you really need to use the RegExp constructor is when you're building up a regular expression from separate pieces, dynamically. You have to be careful with quoting forward-slash characters in the expression (/) when you use native regular expression syntax. You don't have to quote them inside [ ] groups, but you do need to double your backslashes.

That regular expression won't match ..\what\ever because it only looks for forward slash at the start. It also won't match a terminal file name longer than two characters. I think a better one would be:

var pathRE = /^\.\.(?:\\[A-Za-z0-9_-]+)+/;

with appropriate changes for the file name characters you expect.

于 2013-09-26T14:07:02.843 回答
3

转义斜线:

/^((\.\./|[a-zA-Z0-9_\/\-\\])*\.[a-zA-Z0-9])/
//          here   __^   and    add slash __^
于 2013-09-26T14:04:08.080 回答