简体   繁体   English

正则表达式匹配字符串中任意位置的一定数量的数字

[英]Regular expression to match a certain number of digits anywhere in a string

I'm trying to use angular's ng-pattern attribute to enforce that the text in an input box matches a particular regular expression. 我正在尝试使用angular的ng-pattern属性来强制输入框中的文本与特定的正则表达式匹配。 I'm doing this for form validation. 我这样做是为了表单验证。 The input I'm using this on is a phone field. 我正在使用它的输入是一个电话字段。 The phone field can accept 10 digit phone numbers but I don't want to require a specific format from my users other than it must contain a 10 digit number in there somewhere. 电话领域可以接受10位数的电话号码,但我不希望我的用户需要特定的格式,除非它必须包含10位数字。 So these would both be valid. 所以这些都是有效的。

  • 555-555-5555 555-555-5555
  • (555) 555-5555 (555)555-5555

On the backend, I would just remove all formatting and store the raw digits. 在后端,我只删除所有格式并存储原始数字。 In the past for this what I've done is to remove all non-numeric characters and then just made sure the length == 10. It's simple enough to do in a couple of lines of code, but is it something regular expressions can handle? 在过去,我所做的就是删除所有非数字字符,然后确保长度== 10.这很简单,可以在几行代码中完成,但它是正则表达式可以处理的东西? This isn't something I've ever tried to make a regular expression do. 这不是我曾试图做正则表达式的事情。 I don't want to support specific formats because I don't care if they accidentally enter an extra space or if they want to type their phone number like this: 55-55-55-55-55. 我不想支持特定的格式,因为我不在乎他们是否意外地输入了额外的空间,或者他们是否想要输入这样的电话号码:55-55-55-55-55。 It really doesn't matter to me, I just want the regex to match if there are 10 digits and no more somewhere in the string. 这对我来说无关紧要,我只想要正则表达式匹配,如果有10个数字,而不是字符串中的某个地方。

Thanks for the help guys! 谢谢你的帮助!

To allow just 10 digits in a string with a regex, no more no less, you can use 只允许带有正则表达式的字符串中的10位数字,不多也不少,您可以使用

^(?:\D*\d){10}\D*$

See demo ( \\D replaced with [^\\d\\n] to exclude newline for demo only). 请参阅演示\\D替换为[^\\d\\n]以排除仅用于演示的换行符)。

The (\\d\\D*?){10} regex will find the match in a string with more than 10 digits. (\\d\\D*?){10}正则表达式将在超过10位数的字符串中找到匹配项。

^(?!(?:.*?\d){11,})[^a-zA-Z\n]+$

Try this.See demo. 试试这个。看看演示。

https://regex101.com/r/iQ4nW0/1 https://regex101.com/r/iQ4nW0/1

您可以为它创建属性类型指令,并使用动态正则表达式设置有效性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM