1

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.

3
  • Assert the number of digits ^(?=[0-9]{9}$)(?:230|420|7456)[0-9]+$ Commented Jun 30, 2022 at 18:01
  • If you use Javascript, the solution of Code Maniac might be the more intuitive one. Commented Jun 30, 2022 at 18:09
  • ^((230|420)[0-9]{6})|(7456[0-9]{5})$ Commented Jun 30, 2022 at 18:23

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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"))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.