Regex to check for first 3 consecutive digits

1.8k views Asked by At

Would like to find out how to validate a string such that first 3 consecutive digits cannot be 8 or 9 consecutively? Example:

88839182 (not valid) 
99923213 (not valid)
98188823 (valid) 
98939117 (valid)

Tried using s.match("([98]){3}") but it doesn't seem to work, as it takes in 989 for first 3 character too.

4

There are 4 answers

4
Bohemian On

Another, simpler way of defining the problem is "does not start with 888 or 999",

It find invalid data:

s.match("^(999|888)")

To find valid data;

!s.match("^(999|888)")
4
Mazdak On

You can use following regex for identifying the 3 consecutive 8 or 9 :

"(?:([98])\1\1)"

Demo

And for matching the numbers that you want you can use a negative look ahead to match numbers that doesn't precede by 3 consecutive 9 or 8:

^(?!(?:([98])\1\1)).*$

Demo

Also as a nice suggestion by @Luv2code you can use following regex that will forced your regex engine to match digits:

(?=^\d+$)(?!([98])\1\1)\d+
0
alexis On

I'll assume your problem statement is correct: You want to (a) find the first triple digit in your digit string, and (b) reject the string if this is 888 or 999. So do it in two steps:

  1. Find and extract the first three consecutive digits.
  2. Reject the string if the match is 888 or 999.

The regexp to match three consecutive digits is simply (\d)\1\1. The rest depends on your programming language (which you don't specify); it almost certainly a way to return the contents of the first match in your digit string.

0
vks On
\b(?!(?:888|999))\d+\b

You can simply do this.See demo.

https://regex101.com/r/vH0iN5/3