Regular expressions – need to help regular expression matching blood type

I am trying to come up with a regular expression to help me validate the blood type field – it should only accept A [– ], B [– ], AB [–] and O [– ].

This is the regular expression I came up with (and tested it with Regex Tester):

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

Now this pattern successfully matches A, B, O [–] but fails for AB [– ].

Anyone can suggest one Is a regular expression suitable for my purpose?

Thank you,
Mi^E

Try:

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

Use square brackets to define a character class, which can only be a single character . The parentheses create a grouping allow it to do what you want. You also don’t need to escape in character classes-because they don’t have their regexy meaning in them.

As you mentioned in the comments, if it’s Is the string you want to match, and has the exact value you want to find, you may need to do the following:

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

If there is no start of string and end of string anchors, things like “helloAB asdads” will match.

I am Try to come up with a regular expression to help me validate the blood type field – it should only accept A [– ], B [– ], AB [–] and O [– ].

This is me The regular expression I came up with (and tested it with Regex Tester):

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

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

Can anyone suggest a regular expression that suits my purpose?

Thank you,
Mi^E

Try:

< pre>(A|B|AB|O)[+-]

Use square brackets to define a character class, which can only be a single character. The brackets create a grouping allow it to do what you want You don’t need to escape in character classes either-because they don’t have their regexy meaning in them.

As you mentioned in the comments, if it is the string you want to match, and it has the To find the exact value, you may need to do the following:

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

If not start of string and end of string anchors, things like “helloAB asdads” will match.

Leave a Comment

Your email address will not be published.