-1

I'm trying to capture a group that has a variety of different forms.

  1. cardType=A&Return=True
  2. cardType=AbC321
  3. Return=False&cardType=C

My current regex is:

cardType=(?<Card Type>.*)&?

This currently captures the 2 and 3, but not in 1 as it also captures Return in that case.

If I do instead:

cardType=(?<Card Type>.*?)&

Then it correctly captures 1, but not 2 and 3.

How do I write a regex that captures it in all 3 cases?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
brajaram
  • 39
  • 1
  • 4

1 Answers1

0

Use:

cardType=(?<CardType>[^&\s]*)

Demo

Two important changes:

  • removed space form group name
  • replaced .*)&? with [^&\s]*)

The second change is more important. When you do .*&?, then &? is never captured, because .* takes the & sign. As in most cases it's better to limit the repetition by limiting scope of accepted charactes to [^&\s] - anything but whitespace or ampersand

mrzasa
  • 22,895
  • 11
  • 56
  • 94
  • Aha, thanks for the help. I see, you use the `[]` to go until you hit either a whitespace or an ampersand. I see putting the `[]` before the * makes it work, but I'm not sure I understand why it has to go before the `*`, instead of after? – brajaram Apr 12 '18 at 22:46
  • Operators, e.g. `*` or `?` affect subpatterns that are before them. So `.*` means "any number of any characters" and [^&]* means "any number of any character but &". `*.` or `*[^&]` make no sense. – mrzasa Apr 12 '18 at 22:50