Need help with Regular Expression to Match Blood Group

前端 未结 5 1138
不知归路
不知归路 2021-01-13 17:06

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 th

5条回答
  •  抹茶落季
    2021-01-13 17:48

    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.

提交回复
热议问题