Regex Lookahead and lookbehind no more than one digit

I am looking to create a RegEx template

  • 8 characters [a-zA_Z]
  • must contain only one digit anywhere on the line

I created this template:

 ^(?=.*[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 
+3
c # regex regex-lookarounds
source share
2 answers

Instead, you can use:

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

The first part will claim that the match contains 8 alphabets or numbers. Once this is ensured, the second part ensures that there is only one number in the match.

EDIT: Explanation:

  • Anchors ^ and $ denote the beginning and end of a line.
  • (?=[0-9a-zA-Z]{8}) states that the match contains 8 alphabets or numbers.
  • [^\d]*\d[^\d]* will mean that there is only one digital character and the remaining non-character characters. Since we have already claimed that the input contains numbers or alphabets, characters without numbers here are alphabets.
+8
source share

If you want a non-regular expression, 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; } 
0
source share

All Articles