Search code examples
c#regex

Check for at least 1 digit and 1 letter within the first n characters


I have to check if there are numbers and letters in the first 5 characters of an order number from a customer. There must always be at least 1 letter and at least 1 number.

Internal information that are not relevant for the check can be appended after the order number. Therefore, only the first 5 characters need to be checked.

The position of the characters is different each time.

So far I have

\A\w{5}

But how can I check that there is always 1 letter and 1 number?

String examples:

Correct: A1Aaa, 1AAAA, 1111a, A1A1A. AAA123!A

Incorrect: aaAAA, 11111, A AAA, A1, AA!1AA !A11

There are different requirements for checking the order numbers for each customer. I want to save the regex expression in the DB to dynamically load and check the order numbers for each customer with their regex expression.

This above is the requirement of one customer. Another one has e.g. 7 characters with only numbers.

It would be great if someone here could help me!


Solution

  • You can use

    ^(?=\w{0,4}\p{L})(?=\w{0,4}\d)\w{5}
    

    See the regex demo.

    Details:

    • ^ - start of a string
    • (?=\w{0,4}\p{L}) - right after, there should be 0 to 4 word chars followed with a letter
    • (?=\w{0,4}\d) - an there must be a digit within the first 5 word chars, too
    • \w{5} - then match and consume 5 word chars.