正则表达式行为的差异

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

Difference in regex behavior

问题

我正在尝试构建一个正则表达式来匹配一个字段,该字段应该恰好包含9位数字。

我使用以下正则表达式:

/^\d{9,9}$/

现在的问题是,在执行以下操作时:

/^\d{9,9}$/.test("123456789") // 返回true

但是,当我尝试在Yup的matches方法中使用完全相同的正则表达式(在myRegex中传递),如下所示:

'myField': yup
    .string()
    .nullable()
    .required('Field is required')
    .max(9, 'Max length 9')
    .matches(myRegex, {
        message: 'Field is invalid',
    }),

对于相同的输入,即123456789,我会得到无效的消息。只是想知道为什么会出现这种情况?

更新:
Yup使用value.search(regex),所以在我的情况下,它运行了"123456789" .search(/^\d{9,9}$/)

不确定以上是否是问题的原因?

英文:

I am trying to build a regex to match a field which should contain exactly 9 digits

I use the below regex

/^\d{9,9}$/

Now, the issue is while doing

/^\d{9,9}$/.test("123456789") //returns true

But, when I try to use the same exact regex (passed in myRegex below) using Yup's matches

'myField': yup
            .string()
            .nullable()
            .required('Field is required')
            .max(9, `Max length 9`)
            .matches(myRegex, {
                message: 'Field is invalid',
            }),

I get invalid message for the same input i.e. 123456789

Just wondering why that is the case ?

Update:
Yup uses value.search(regex) and so, in my case, it runs "123456789".search(/^\d{9,9}$/)

Not sure if above is the issue ?

答案1

得分: 1

似乎你在解决方案中使用了错误的正则表达式。

问题出现在当使用Yup的search()方法与正则表达式一起使用时。search()方法返回第一个匹配的索引,而不评估整个字符串。

由于“123456789”连续包含9个数字,正则表达式被满足,search()方法返回第一次出现的索引,即0。由于0是一个真值,Yup将其解释为匹配失败并返回无效的消息。

这是你可以尝试的正则表达式:/^\d{9}$/

英文:

Seems like you are using wrong regex for your solution

The problem arises when Yup's search() method is used with the regular expression. The search() method returns the index of the first match, and it does not evaluate the full string.

Since "123456789" contains 9 digits consecutively, the regular expression is satisfied, and the search() method returns the index of the first occurrence, which is 0. Since 0 is a truthy value, Yup interprets it as a failed match and returns the invalid message.

Here is the regex you can try with /^\d{9}$/

huangapple
  • 本文由 发表于 2023年6月9日 14:31:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76437754.html
匿名

发表评论

匿名网友

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

确定