Search code examples
regexstringexpressionstring-matching

Regular expression for prefix numeric values and a specific range of letters from the alphabet


I need a regular expression that will allow me to enter a specific set of characters.

The regular expression should not allow me to enter numeric values only unless the numeric value entered is prefix with '9999'.

It should also not allow me to enter any string of data if it contains any letter pass "F" from the alphabet.

And lastly, the length of the value entered should not exceed 12 characters/digits

Is the above possible?

I have a regular expression that will take care of the length and numeric values only but I need assistance with the prefix and letters pass "F".

 ^(?![0-9]*$)[a-zA-Z0-9]{12}$

Valid Samples:

 3847a654b321
 3899c654b876
 999946578432
 999975620983

Invalid Samples:

 874k459m8723
 546p34s85734
 543216789012
 243567890218

Hope this helps.


Solution

  • Brief

    Based on the following information:

    • All digits, must begin with 9999 or digits and characters in the a-f range only
    • Max length of 12 characters

    Code

    This is the regex you're looking for:

    See this regex in use here

    ^(?:9{4}\d{8}|(?=.*[a-f].*)[\da-f]{12})$
    

    Explanation

    • Assert position at start of line/string
    • Match 4 9s followed by 8 of any digit OR ensure there is a character in the a-f range ahead and ensure it's made up of 12 of any digit or character in the a-f range
    • Assert position at end of line/string