为什么和我得到:“无效的正则表达式.未捕获的语法错误.无效的转义."? [英] Why and I getting: "Invalid regular expression. Uncaught SyntaxError. Invalid escape."?
问题描述
我正在尝试创建一个 html 输入标签,它只接受以 2 种格式之一输入的数字,并拒绝所有其他输入.
Im trying to create an html input tag that accepts only numbers entered in 1 of 2 formats, and reject all other input.
我只想接受这些格式的数字,包括需要破折号:
I want to accept numbers in these formats only, including requiring the dashes:
1234-12
和
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 />
Chrome 中的 Devtools 控制台错误:
Devtools Console Error in Chrome:
模式属性值^(\d{4}\-\d{2}\-\d{2})|(\d{4}\-\d{2})$
不是有效的正则表达式:未捕获的语法错误:无效的正则表达式:/^(\d{4}-\d{2}-\d{2})|(\d{4}-\d{2})$/: 无效转义
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
推荐答案
你不应该在 ES6 正则表达式中的字符类之外使用 u
标志转义连字符 当前版本的 Chrome 和 FF 中 pattern
正则表达式中默认使用的那个.
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).
另外,模式属性中的正则表达式默认是锚定的,去掉多余的^
和$
,使用可选组缩短模式
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="\d{4}-\d{2}(-\d{2})?"
HTML5 pattern
属性中的这个正则表达式意味着:
This regex in the HTML5 pattern
attribute means:
\d{4}-\d{2}
- 匹配 4 位数字,-
,然后是字符串开头的 2 位数字(-\d{2})?
- 并可选择匹配-
和字符串末尾的 2 位数字.
\d{4}-\d{2}
- match 4 digits,-
, and then 2 digits from the start of string(-\d{2})?
- and optionally match a-
and then 2 digits at the end of the string.
这篇关于为什么和我得到:“无效的正则表达式.未捕获的语法错误.无效的转义."?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!