0

I need to match the first few characters of a string. The match is true if:

  1. The first character is a letter (case insensitive)
  2. The second character is either a digit or a letter
  3. If the second character is a digit, the match is returned true
  4. If the second character is a letter, the third character must be a digit
  5. The pattern will ignore all other subsequent characters in the string

Examples:

AB1ghRjh  //true
c1        //true
G44       //true
Tt7688    //true
kGF98d    //false
4FG3      //false
4 5a      //false
RRFDE     //false

Would appreciate if anyone could supply an example.

Thanks a lot!

1
  • 1
    This may be a beginner question, but it is clear and has a good answer. Commented Jul 6, 2018 at 9:53

2 Answers 2

2

Regex would be

^[a-zA-Z](\d|[a-zA-Z]\d).*
Sign up to request clarification or add additional context in comments.

Comments

1
/^(?:[a-z]{2}|[a-z])\d.*$/im

Explanation:

^   # Start of string
    (?: # Start non-capturing group
        [a-z]{2}    # Two letter
        |   # OR
        [a-z]   # One letter
    )   # End of non-capturing group
    \d  # At least a digit here
    .*  # Escape all other characters
$   # End of string

i flag means case insensitive, m flag means make ^ & $ do matching on each line (optional if your input hasn't newlines)

Live demo

Then using preg_match function to match the strings:

if(preg_match("/^(?:[a-z]{2}|[a-z])\d.*$/i", "AB1ghRjh"))
{
    echo "Matched";
}

2 Comments

Wow - thanks to all replies, but especially to yours for taking the time to explain it all out and for including a sample PHP statement. Really appreciate it!!!
After 5 years I could see that the regex in this answer is somehow wordy. Someone could write ^[a-z]{1,2}\d instead with i flag enabled.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.