0

I have

Console.WriteLine(Regex.Match("<Anything1>Manadatory=Optional<Anything2>", 
    @"(?<M>.+?)[ \t]*?(?<O>=Optional)?"
  ).Groups["O"].Value);

Presence of '=Optional' is optional. I'd expect that if I have '?' next to its pattern, that string will be matched but instead of it empty string is matched. How can I write a pattern so =Optional is matched if it is there and O group is empty if =Optional isn't there ?

Thanks

  • If you use `Regex.Matches`, the last match will have `O` group populated. I think all you need is anchors: [`^(?.+?)[ \t]*?(?=Optional)?$`](http://regexstorm.net/tester?p=%5e%28%3f%3cM%3e.%2b%3f%29%5b+%5ct%5d*%3f%28%3f%3cO%3e%3dOptional%29%3f%24&i=Manadatory%3dOptional) – Wiktor Stribiżew Dec 29 '16 at 14:08
  • Try Derek's http://derekslager.com/blog/posts/2007/09/a-better-dotnet-regular-expression-tester.ashx Regular Expression Tester for verification your regex. – honzakuzel1989 Dec 29 '16 at 14:12
  • @Wiktor - Thank you. However, I made my question more explicit. Matching string from start to end is only one option. Unfortunately, that option doesn't apply to my scenario. –  Dec 29 '16 at 15:04
  • Actually, it does not change much. Your main question is how to get `O` group populated when it matches and empty upon no match. ***That is exactly what your pattern is doing now.*** You just try with `Regex.Matches(str, @"your-pattern").Cast().Select(m=>m.Groups["O"].Value).ToList()` and print the results, the last item will be that substring you are searching for as it was matched *the last* (since your pattern matches 1 char with `.+?` each time before the `O` pattern). You must provide a real life scenario. – Wiktor Stribiżew Dec 29 '16 at 15:06

0 Answers0