1

I have this string:

of cabbages and kings and more kings

I want to match based on this criteria:

- Any instance of "king"
- Any instances of "cab" OR "goat"
- No instances of "bill"

This regex works for IsMatch():

^(?=.*?(king))(?=.*?(cab|goat))(?=.*?(bill))

But it just returns 1 group with a 0 length. Is there a way to have it return matching groups so that we can read the matched text after?

Jon Tackabury
  • 47,710
  • 52
  • 130
  • 168

1 Answers1

1

Because your pattern use only lookarounds,it would only check for the pattern but would never include the matched pattern except any groups in lookarounds..

If you want to capture the complete string,use the Match method with the given pattern

^(?=.*king)(?=.*(?:cab|goat))(?=.*bill).*$

This regex would match the complete string in group 0 if it matches the pattern..

Anirudha
  • 32,393
  • 7
  • 68
  • 89
  • Instead of matching the entire string, is it possible to return matches (or groups) for each term? Like "king" and "cab"? – Jon Tackabury Mar 08 '13 at 18:42
  • @JonTackabury yes..you have to use `match` method..your regex would work perfectly..i.e it would capture the words in the lookahead since you are using groups in the lookahead.. – Anirudha Mar 08 '13 at 18:57
  • This seems to just capture the entire string, not just the parts that match, like "king". – Jon Tackabury Mar 08 '13 at 19:07
  • @JonTackabury Can you provide an example string you are working with? The logic above seems to work fine for me. *edit - Never mind; I just noticed your example above. Even that works fine for me with Some1.Kill.The.DJ's suggestion. – Kenneth K. Mar 08 '13 at 20:25