Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reg Ex验证程序在javascript中不工作_Javascript_Regex_Validation - Fatal编程技术网

Reg Ex验证程序在javascript中不工作

Reg Ex验证程序在javascript中不工作,javascript,regex,validation,Javascript,Regex,Validation,上面是我用来验证输入的目录路径的代码。是验证程序网站的链接,它显示了与C:\或D:\Abcd\List.odt的完美匹配。但是当我尝试运行上面的JavaScript时,它失败了。当正则表达式字符串'[\w]:\\\.'被JavaScript的正则表达式引擎解析时,它会将\w视为转义字符,因为\w作为转义字符没有特殊意义,所以它只会被视为w 要解决这个问题,您需要像这样转义\ regularExpression = '[\w]:\\.*'; function validate() { deb

上面是我用来验证输入的目录路径的代码。是验证程序网站的链接,它显示了与
C:\
D:\Abcd\List.odt
的完美匹配。但是当我尝试运行上面的JavaScript时,它失败了。

当正则表达式字符串
'[\w]:\\\.'
被JavaScript的正则表达式引擎解析时,它会将
\w
视为转义字符,因为
\w
作为转义字符没有特殊意义,所以它只会被视为
w

要解决这个问题,您需要像这样转义
\

regularExpression = '[\w]:\\.*';

function validate() {
  debugger;

  var regex = new RegExp(regularExpression);
  var ctrl = document.getElementById('txtValue');

  if (regex.test(ctrl.value)) {
    return true;
  } else {
    return false;
  }
}
var regularExpression = '[\\w]:\\.*';
或者像这样使用RegEx-literal

regularExpression = '[\w]:\\.*';

function validate() {
  debugger;

  var regex = new RegExp(regularExpression);
  var ctrl = document.getElementById('txtValue');

  if (regex.test(ctrl.value)) {
    return true;
  } else {
    return false;
  }
}
var regularExpression = '[\\w]:\\.*';

正如Cyrbil在评论中指出的,字符类
[\w]
仅与
\w
相同。因此,当JavaScript的正则表达式引擎解析正则表达式字符串
'[\w]:\\.*.
时,可以安全地省略
\w
周围的方括号,它将
\w
视为转义字符,并且由于
\w
作为转义字符没有特殊意义,因此它将仅被视为
w

要解决这个问题,您需要像这样转义
\

regularExpression = '[\w]:\\.*';

function validate() {
  debugger;

  var regex = new RegExp(regularExpression);
  var ctrl = document.getElementById('txtValue');

  if (regex.test(ctrl.value)) {
    return true;
  } else {
    return false;
  }
}
var regularExpression = '[\\w]:\\.*';
或者像这样使用RegEx-literal

regularExpression = '[\w]:\\.*';

function validate() {
  debugger;

  var regex = new RegExp(regularExpression);
  var ctrl = document.getElementById('txtValue');

  if (regex.test(ctrl.value)) {
    return true;
  } else {
    return false;
  }
}
var regularExpression = '[\\w]:\\.*';

正如Cyrbil在评论中指出的,字符类
[\w]
仅与
\w
相同。因此,您可以放心地省略
\w

周围的方括号,这样回答如此频繁的问题毫无意义。你应该将它们标记为重复的。这是他试图验证一条路径,也许是建议一种正确的方法?回答如此频繁的问题毫无意义。你应该把它们标记为重复的。这是他试图验证一条路径,也许能建议一种正确的方法吗?@Tushar:你能;请使用filepath注册表项。与上述filepath注册表项相同的问题:^(?[a-zA-Z]\:\\\[\w\.]+\[\w.$]+\(?:[\w]+\)*\w([\w.])+$@Tushar:你可以吗;使用文件路径注册表项时遇到与上述文件路径注册表项相同的问题:^(?[a-zA-Z]\:\\\[\w\.]+\[\w.$]+\(?:[\w]+\)*\w([\w.]))+$