0

I want to build a regex for a string that will contain 8 numeric characters[0-9] and 1 alphabetic character[a-z] means a total of 9 characters. The position of the alphabetical character and numeric characters can be any means numeric characters can come first like 12345678a or alphabetical character can come at the start like a12345678.

For above, I have tried below regex:

 (([0-9]{8}[^.aeiou])|([^.aeiou][0-9]{8}))

But it's selecting a string which has more than 9 characters. I have tested it on regex & you can check it's screenshot below.

Image

Can anyone please help me to solve it? Thanks for your time.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Rajat
  • 1
  • 2
  • 1
    *"But it's selecting a string which has more than 9 characters"* Because you don't have any start-of-input / end-of-input assertions. You need a `^` at the start and a `$` at the end. (I haven't checked the middle.) – T.J. Crowder May 19 '20 at 21:07
  • i think `^.` is causing the issue. `[0-9]{8}[aeiou]|[aeiou][0-9]{8}` worked for me. – Jimish Fotariya May 19 '20 at 21:13
  • `\b([0-9]{8}[a-z]|[a-z][0-9]{8})\b` according to your description. – Jarod42 May 19 '20 at 21:18
  • @JimishFotariya, It's not working for me at all. – Rajat May 19 '20 at 22:58
  • @Jarod42, Not working. – Rajat May 19 '20 at 23:07
  • From [Demo](https://regex101.com/r/gP4rxy/1), it seems to match you expectations. – Jarod42 May 19 '20 at 23:16
  • As I understand the letter can be anywhere in the string. If so, you could use the following regular expression for verification: `^(?=.{9}$)\d*[a-z]\d*$`. This breaks the testing into parts. The beginning-of-line anchor `^` and *positive lookahead* `(?=.{9}$)` asserts that the string contains `9` characters. The beginning-of-line anchor and `\d*[a-z]\d*$` asserts that the string contains one lowercase letter, anywhere in the string, and all other characters, if any, are digits. The positive lookahead ensures there must be `8` digits. – Cary Swoveland May 20 '20 at 00:04

0 Answers0