Question

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
Was it helpful?

Solution

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.

OTHER TIPS

If you want a non regex solution, I wrote this for a small project :

public static bool ContainsOneDigit(string s)
{
    if (String.IsNullOrWhiteSpace(s) || s.Length != 8)
        return false;
    int nb = 0;
    foreach (char c in s)
    {
        if (!Char.IsLetterOrDigit(c))
            return false;
        if (c >= '0' && c <= '9') // just thought, I could use Char.IsDigit() here ...
            nb++;
    }
    return nb == 1;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top