invalid escape in pattern HTML/Javascript

匿名 (未验证) 提交于 2019-12-03 08:48:34

问题:

I am trying to make an input field that uses a pattern to check if the input is a valid windows file path. The pattern i have is

/^(?:[\w]\:|\\)(\\[a-zA-Z_\-\s0-9\.()~!@#$%^&=+';,{}\[\]]+)+\.(exe)$/g 

however when putting this into the pattern attribute of an input field it says (in console)

Pattern attribute value ^(?:[\w]:|\)(\[a-zA-Z_-\s0-9.()~!@#$%^&=+';,{}[]]+)+.(exe)$ is not a valid regular expression: Uncaught SyntaxError: Invalid regular expression: /^(?:[\w]:|\)(\[a-zA-Z_-\s0-9.()~!@#$%^&=+';,{}[]]+)+.(exe)$/: Invalid escape

I have tried several different ways of writing this but none seem to work.

回答1:

You only need to escape the characters in the character class that must be escaped otherwise, you will always get this error.

Use

pattern="(?:\w:|\\)(\\[\w\s.()~!@#$%^&=+';,{}[\]-]+)+\.exe" 

See the JSFiddle

Details:

  • The hyphen must be at the end of the character class
  • The ] inside the character class must be escaped
  • The [ and . must not be escaped
  • The : must never be esacaped, it is never a special character
  • [a-zA-Z0-9_] = \w
  • The pattern is always anchored by default, you need no ^ and $ anchors.


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!