英文:
How to write regex strings for the input pattern attribute
问题
我有一个在JavaScript中工作但不作为input
标签的pattern
属性的正则表达式。
下面的正则表达式测试字符串是否至少有3个非数字字符。
/(?=^([^\d]*)$)(?=(\w){3,})/
在一个"input"标签中,我使用了相同的正则表达式字符串:
pattern="(?=^([^\d]*)$)(?=(\w){3,})"
这不起作用,因为伪类:invalid
始终处于活动状态。
我应该如何构造pattern
中的正则表达式字符串?
英文:
I have a regex that works in Javascript but not as a pattern
attribute of the input
tag.
The regex below tests if the string has at least 3 chars which are not numbers.
/(?=^([^\d]*)$)(?=(\w){3,})/
In an "input" tag, I used the same regex string:
pattern="(?=^([^\d]*)$)(?=(\w){3,})"
This does not work as the pseudo-class :invalid
is always active.
How should I formulate the regex string in the pattern?
答案1
得分: 1
你应该查看pattern
属性文档。注意:
- 现在使用
v
标志编译pattern
属性的正则表达式。 anchoredPattern
是^(?:
,后跟*pattern
*,然后是)$
的总和。
因此,你的第一个(?=^([^\d]*)$)(?=(\w){3,})
模式实际上被编译为/^(?:(?=^([^\d]*)$)(?=(\w){3,}))$/v
,并且不匹配任何字符串,因为在字符串的开头之后,必须有字符串的结束,但是前瞻需要至少三个单词字符在开头。
既然你只需要匹配至少三个字符且不包含数字的字符串,你可以简单地使用
pattern="\D{3,}"
它将被编译为/^(?:\D{3,})$/v
,并且将匹配你所需的内容。
英文:
You should check the pattern
attribute documentation. Note:
- The pattern attribute regex is compiled with
v
flag now - The
anchoredPattern
is a sum of^(?:
, followed bypattern
, followed by)$
.
So, your first (?=^([^\d]*)$)(?=(\w){3,})
pattern is actually compiled as /^(?:(?=^([^\d]*)$)(?=(\w){3,}))$/v
and does not match any string because right after the start of string, there must be the string end, but lookaheads require at least three word characters at the start.
Since all you need is to match a string that has at least three chars and contains no digits, you can simply use
pattern="\D{3,}"
It will be compiled as /^(?:\D{3,})$/v
and will match what you need.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论