为什么和我得到:“无效的正则表达式。未捕获的SyntaxError。无效的逃脱。“?

时间:2020-12-08 16:03:34

Im trying to create an html input tag that accepts only numbers entered in 1 of 2 formats, and reject all other input.

我试图创建一个html输入标记,只接受以2种格式之一输入的数字,并拒绝所有其他输入。

I want to accept numbers in these formats only, including requiring the dashes:

我想接受这些格式的数字,包括要求破折号:

1234-12

and

1234-12-12

note: this is not for dates, but rather legal chapter numbers

注意:这不是日期,而是法律章节编号

Everything I am reading about regex says that the following should work, but it isn't.

我正在阅读的关于正则表达式的所有内容都表明以下内容应该有效,但事实并非如此。

<input class="form-control"                       type="text"                       pattern="^(\d{4}\-\d{2}\-\d{2})|(\d{4}\-\d{2})$"                       required />

Devtools Console Error in Chrome:

Chrome中的Devtools控制台错误:

Pattern attribute value ^(\d{4}\-\d{2}\-\d{2})|(\d{4}\-\d{2})$ is not a valid regular expression: Uncaught SyntaxError: Invalid regular expression: /^(\d{4}-\d{2}-\d{2})|(\d{4}-\d{2})$/: Invalid escape

模式属性值^(\ d {4} \ - \ d {2} \ - \ d {2})|(\ d {4} \ - \ d {2})$不是有效的正则表达式:未捕获的SyntaxError :无效的正则表达式:/ ^(\ d {4} - \ d {2} - \ d {2})|(\ d {4} - \ d {2})$ /:无效的转义

1 个解决方案

#1


3  

You should not escape the hyphen outside a character class in ES6 regex used with the u flag (the one used by default in pattern regexps in the current versions of Chrome and FF).

您不应该使用与u标志一起使用的ES6正则表达式中的字符类之外的连字符(在当前版本的Chrome和FF中默认使用模式正则表达式)中的连字符。

Also, the regex in the pattern attribute is anchored by default, remove the redudant ^ and $ and shorten the pattern by using an optional group

此外,默认情况下锚定pattern属性中的正则表达式,删除还原剂^和$并使用可选组缩短模式

pattern="\d{4}-\d{2}(-\d{2})?"

This regex in the HTML5 pattern attribute means:

HTML5模式属性中的此正则表达式表示:

  • \d{4}-\d{2} - match 4 digits, -, and then 2 digits from the start of string
  • \ d {4} - \ d {2} - 匹配4位数字, - ,然后是字符串开头的2位数字

  • (-\d{2})? - and optionally match a - and then 2 digits at the end of the string.
  • ( - \ d {2})? - 并且可选地匹配字符串末尾的 - 然后2位数字。

#1


3  

You should not escape the hyphen outside a character class in ES6 regex used with the u flag (the one used by default in pattern regexps in the current versions of Chrome and FF).

您不应该使用与u标志一起使用的ES6正则表达式中的字符类之外的连字符(在当前版本的Chrome和FF中默认使用模式正则表达式)中的连字符。

Also, the regex in the pattern attribute is anchored by default, remove the redudant ^ and $ and shorten the pattern by using an optional group

此外,默认情况下锚定pattern属性中的正则表达式,删除还原剂^和$并使用可选组缩短模式

pattern="\d{4}-\d{2}(-\d{2})?"

This regex in the HTML5 pattern attribute means:

HTML5模式属性中的此正则表达式表示:

  • \d{4}-\d{2} - match 4 digits, -, and then 2 digits from the start of string
  • \ d {4} - \ d {2} - 匹配4位数字, - ,然后是字符串开头的2位数字

  • (-\d{2})? - and optionally match a - and then 2 digits at the end of the string.
  • ( - \ d {2})? - 并且可选地匹配字符串末尾的 - 然后2位数字。