Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex Lookahead and lookbehind at most one digit

I'm looking for create RegEx pattern

  • 8 characters [a-zA_Z]
  • must contains only one digit in any place of string

I created this pattern:

^(?=.*[0-9].*[0-9])[0-9a-zA-Z]{8}$

This pattern works fine but i want only one digit allowed. Example:

aaaaaaa6   match
aaa7aaaa   match

aaa88aaa   don't match
aaa884aa   don't match
aaawwaaa   don't match
like image 913
Eslam Totti Avatar asked Jan 23 '26 12:01

Eslam Totti


1 Answers

You could instead use:

^(?=[0-9a-zA-Z]{8})[^\d]*\d[^\d]*$

The first part would assert that the match contains 8 alphabets or digits. Once this is ensured, the second part ensures that there is only one digit in the match.

EDIT: Explanation:

  • The anchors ^ and $ denote the start and end of string.
  • (?=[0-9a-zA-Z]{8}) asserts that the match contains 8 alphabets or digits.
  • [^\d]*\d[^\d]* would imply that there is only one digit character and remaining non-digit characters. Since we had already asserted that the input contains digits or alphabets, the non-digit characters here are alphabets.
like image 128
devnull Avatar answered Jan 25 '26 00:01

devnull



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!