Regex to block a phone number that contains same d

2019-09-05 17:49发布

i would like to add a regex to check if a phone number contains the same digits more than n times. this is what i tried :

  ^0[1-9]([-. ]?[0-9]{2}){4}$

how can i make it ? thanks.

3条回答
做个烂人
2楼-- · 2019-09-05 18:10

You just need to check for any repeating character n times or more. First we need to determine which characters we want to catch. Second we need to get that single character from the capture group using the backslash + n. Finally we need to say how many times it should repeat from. In this scenario I don't think it needs to validate the entire number, just the fact there are the same repeated characters. So in order to catch any repeating number 4 or more times we can do:

'06000000000'.test(/([0-9])\1{3,}/); // return true
'12344445678'.test(/([0-9])\1{3,}/); // return true
'01234567890'.test(/([0-9])\1{3,}/); // return false

([0-9]) this is what we want to check, in this case any number from 0 to 9

\1 get the value from the first capture group

{3,} check this value is repeating 3 or more times, because we've already got that first character matched in our capture group. 3 + 1 = 4 naturally.

查看更多
3楼-- · 2019-09-05 18:10

You could go for

^\d*(\d)\1{3}\d*$

These numbers can be discarded, see a demo on regex101.com.

查看更多
疯言疯语
4楼-- · 2019-09-05 18:23

you may try this pattern:

(\d)\1{3,}

(\d) indicates digits number

(\d)\1 Matches the digits of a numbered subexpression

(\d)\1{2,} matches the digits 1+2 and more times.

(\d)\1{3,} matches the digits 1+3 and more times.

(\d)\1{3} matches exactly 1+3 times

\1 counts 1 already. That's why \1{3} is 1+3.

查看更多
登录 后发表回答