-2

I have a string abcdefgh,

i want to check if the last two characters are alpha numeric/alphabets but not numeric

i.e. it can end in a1, 1a, aa but not 11

are there any regex gurus who can chipin

The regex should return the below results for the strings

abcd - True abc1d - True abcd1 - True abc12 - false

Mohammed Rafeeq
  • 2,586
  • 25
  • 26

4 Answers4

2

This should do it:

^.*(\d[a-zA-Z]|[a-zA-Z](\d|[a-zA-Z]))$

Online regex tool demo here.

Meaning:

^                       the beginning of the string
.*                      any character except \n (0 or more times)
(                        
 \d[a-zA-Z]             a digit (0-9) followed by any character of a to z, A to Z
 |                      OR
 [a-zA-Z]               any character of a to z, A to Z followed by
 (\d|[a-zA-Z])          a digit or any character of a to z, A to Z
)                         
$                       end of the string

Notice this matches the whole string, not only the two last chars, having those at the matched group one.

acdcjunior
  • 132,397
  • 37
  • 331
  • 304
1

So, a letter and a digit, or a digit and a letter, or two letters?

([a-zA-Z]\d|\d[a-zA-Z]|[a-zA-Z][a-zA-Z])$

Depending on the regex system you're using, you can also use character classes such as :alpha:, but this one will work for all of them. Some regex syntaxes need a backslash in front of the parentheses and/or pipe symbol.

Peter Westlake
  • 4,894
  • 1
  • 26
  • 35
0

You can use

^.*[A-Za-z].|.[A-Za-z]$

Online test

Sven Hohenstein
  • 80,497
  • 17
  • 145
  • 168
0

You can use :

^.*([a-zA-Z]{2}|(\d[a-zA-Z])|([a-zA-Z]\d))$

DEMO

EXPLANATION:

enter image description here

Sujith PS
  • 4,776
  • 3
  • 34
  • 61