Home > Software engineering >  Regex validating string of numbers
Regex validating string of numbers

Time:07-01

I am trying create regex witch will start with some number like 230, 420, 7456. Then could be some number in interval 1-9 but the final length must be 9.

For example 230888333 or 745623777

I create this:

([(230|420|7456)[0-9]{1,}]{9})

But it is not correct. Any idea how to make this correct?

Thaks.

CodePudding user response:

The pattern that you tried is not anchored, and the current notation uses a character class [...] instead of a grouping (the ]{9} part at the end repeats 9 times a ] char)


If you use C# then use [0-9] to match a digit 0-9.

You can either assert 9 digits in total:

^(?=[0-9]{9}$)(?:230|420|7456)[0-9] $

Regex demo

Or write an alternation for different leading lengths of digits:

^(?:(?:230|420)[0-9]{6}|7456[0-9]{5})$

Regex demo

CodePudding user response:

You can simply add a check for length first and then simple regex

function checkString(str){
  return str.length === 9 && /^(?:230|420|7456)\d $/.test(str)
}

console.log(checkString("230888333"))
console.log(checkString("745623777"))
console.log(checkString("123"))
console.log(checkString("230888333123"))

  • Related