Home > Software design >  Regex not matching patern
Regex not matching patern

Time:08-10

I want to match a blood group letter and number A from the string A positive (A ).

I have this pattern, (\([a-zA-Z] (\ |-)\))\w but it doesn't work. I'll be glad if one can point out what I'm doing wrong

CodePudding user response:

The reason why your regular expression is not working, is because you specify that the pattern must match 1 or more instances of any word character \w , after the parenthesis ends (AB-)triestomatchthis. Given that your string does not contain any characters after that, the pattern is not satisfied. Your current pattern matches the blood type and polarity in parentheses, only if it is followed by word characters:

  • (A )loremipsum
  • (B-)willOnlyMatchThis

But will not match:

  • (A )
  • (B-)

Therefore the solution must remove the problematic token matching. Two possible solutions and their rationale are provided below:

  1. (\(\w \ ?\-?\)).

You will note that the logical or | was not used to match the polarity of the number. Instead we implemented two quantifiers ? to avoid an unnecessary capture group.

Alternatively if you anticipate strings with parentheses that will not be relevant, such as:

  • "A positive (but double check with the lab) (A )"

a modification of your original attempt works best: (\([a-zA-Z] \ ?\-?\)).

Both solutions were tested for all permutations of blood type and polarity.

Bonus: if you wish to maintain the capture group of the blood polarity, use (\([a-zA-Z] (\ |-)\)).

  • Related