Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need help with Regular Expression to Match Blood Group

Tags:

regex

I'm trying to come up with a regex that helps me validate a Blood Group field - which should accept only A[+-], B[+-], AB[+-] and O[+-].

Here's the regex I came up with (and tested using Regex Tester):

[A|B|AB|O][\+|\-]

Now this pattern successfully matches A,B,O[+-] but fails against AB[+-].

Can anyone please suggest a regex that'll serve my purpose?

Thanks, m^e

like image 778
miCRoSCoPiC_eaRthLinG Avatar asked Jun 17 '09 08:06

miCRoSCoPiC_eaRthLinG


1 Answers

Try:

(A|B|AB|O)[+-]

Using square brackets defines a character class, which can only be a single character. The parentheses create a grouping which allows it to do what you want. You also don't need to escape the +- in the character class, as they don't have their regexy meaning inside of it.

As you mentioned in the comments, if it is a string you want to match against that has the exact values you are looking for, you might want to do this:

^(A|B|AB|O)[+-]$

Without the start of string and end of string anchors, things like "helloAB+asdads" would match.

like image 188
Paolo Bergantino Avatar answered Sep 17 '22 15:09

Paolo Bergantino