如何为输入模式属性编写正则表达式字符串

huangapple go评论66阅读模式
英文:

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 by pattern, 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.

huangapple
  • 本文由 发表于 2023年5月29日 20:51:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/76357548.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定