Home > Enterprise >  How to make regex that accepts string which contains 0-9 minimum 2 times and might contain "%&q
How to make regex that accepts string which contains 0-9 minimum 2 times and might contain "%&q

Time:10-05

Eg of Strings

Valid

  1. 12
  2. #
  3. 78%
  4. 12***3
  5. *1*7

Invalid

  1. 8
  2. *7
  3. 6%
  4. AB
  5. %4*

I have tried many regexes but none of them worked for all cases.

The most closet result found for the regex was ^([*%]*[0-9]{2,}[*%\d]*)$.

If anyone can help me build this regex it would be helpful. Thank you so much :)

CodePudding user response:

You can use

^(?:[*%]*\d){2}[*%\d]*$

See the regex demo.

Details:

  • ^ - start of string
  • (?:[*%]*\d){2} - two occurrences of zero or more * or % chars followed with a digit
  • [*%\d]* - zero or more digit, * or % chars
  • $ - end of string.

See a JavaScript demo below:

const texts = ['12','#','78%','12***3','*1*7', '8','*7','6%','AB','%4*'];
const re = /^(?:[*%]*\d){2}[*%\d]*$/;
for (const text of texts) { 
  console.log(text, '->', re.test(text));
}

  • Related