英文:
Valid Regex causes "Unable to check" if used as HTML input's pattern
问题
由于该模式不是有效的正则表达式,无法检查
<input pattern='/^[a-zA-Zà-úÀ-Ú0-9äöüÄÖÜß@\s\+\-\_\.\,\{\}\[\]\(\)\#\']+$/'>
。无效的正则表达式中存在无效的身份转义。
英文:
> Unable to check <input pattern='/^[a-zA-Zà-úÀ-Ú0-9äöüÄÖÜß@\s+-_.,{}[]()#']+$/'> because the pattern is not a valid regexp: invalid identity escape in regular expression
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
First Try: <br />
<input type="text" pattern="/^[a-zA-Zà-úÀ-Ú0-9äöüÄÖÜß@\s\+\-\_\.\,\{\}\[\]\(\)\#\']+$/">
<br />
Second Try: <br />
<input type="text" pattern="[a-zA-Zà-úÀ-Ú0-9äöüÄÖÜß@\s\+\-\_\.\,\{\}\[\]\(\)\#\']+">
<!-- end snippet -->
答案1
得分: 1
引用MDN关于pattern
属性的说明:
> ... 在模式文本周围不应指定正斜杠。
正斜杠在JavaScript中用于表示正则表达式文字。
从同一页引用:
> ... 在编译正则表达式时指定了**'u'标志**,因此该模式被视为Unicode代码点的序列,而不是ASCII。
并引用MDN的正则表达式指南:
> * Unicode正则表达式不支持所谓的“身份转义”;
> 也就是说,不需要转义反斜杠的模式会被有效地忽略。...
这意味着只有必需的字符转义是有效的。
您还应该注意...(引用自同一页)
> * 在字符类内,'-'字符的解释方式不同。特别地,对于Unicode正则表达式,只有当它出现在字符类的开头或结尾时,'-'才被解释为文字'-',而不是范围的一部分。
总之,您的固定模式的第一个版本可能如下所示:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
<input type="text" pattern="^[a-zA-Zà-úÀ-Ú0-9äöüÄÖÜß@\s+\-_\.,\{\}\[\]\(\)#']+$">
<!-- end snippet -->
英文:
Quoting MDN on the pattern
attribute:
> ... No forward slashes should be specified around the pattern text.
The forward slashes are JavaScript syntax for regular expression literals.
Quoting from the same page:
> ... the 'u' flag is specified when compiling the regular expression, so that the pattern is treated as a sequence of Unicode code points, instead of as ASCII.
And quoting MDN's Guide Regular expressions:
> * Unicode regular expressions do not support so-called "identity escapes";
> that is, patterns where an escaping backslash is not needed and
> effectively ignored. ...
This means only required character escapes are valid.
You should also be aware that ... (quoting from the same page)
> * The -
character is interpreted differently within character classes. In particular, for Unicode regular expressions, -
is interpreted as a literal -
(and not as part of a range) only if it appears at the start or end of the character class.
In conclusion, your first pattern in fixed could look like this:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
<input type="text" pattern="^[a-zA-Zà-úÀ-Ú0-9äöüÄÖÜß@\s+\-_\.,\{\}\[\]\(\)#']+$">
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论