Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
488 views
in Technique[技术] by (71.8m points)

invalid escape in pattern HTML/Javascript

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:

<input id="path" type="text" pattern="^(?:[w]:|)([a-zA-Z_-s0-9.()~!@#$%^&=+';,{}[]]+)+.(exe)$">

An error is displayed in the console saying:

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 ways of writing this pattern, but none seem to work.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:|\)(\[ws.()~!@#$%^&=+';,{}[]-]+)+.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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...