0

I want to trim a string if it starts and/or ends with foo or bar for example and want to get the inner string in a regex group.
For example

"fooTestbar" should be "Test",
"Test2bar" should be "Test2"
and "Test3" should be "Test3".

My current regex is:

^(foo|bar)?(.*)(foo|bar)?$

but this doesnt work, because I cant apply the Quantifier ? to the alternative group((foo|bar)).

My Code

static string returnMatch(string text){
string pattern = @"^(foo|bar)?(.*)(foo|bar)?$";
return System.Text.RegularExpressions.Regex.Match(text, pattern).Groups[2].Value;
}

Any help will be greatly appreciated.

Ria
  • 10,237
  • 3
  • 33
  • 60
Tearsdontfalls
  • 767
  • 2
  • 13
  • 32

2 Answers2

1

You can use this

^(?:foo|bar)?(.*?)(?:foo|bar)?$

You can now match it like this..

return Regex.Match(input,"^(?:foo|bar)?(.*?)(?:foo|bar)?$").Groups[1].Value;
Tearsdontfalls
  • 767
  • 2
  • 13
  • 32
Anirudha
  • 32,393
  • 7
  • 68
  • 89
1

I suggest you to go with

(?:^|(?<=^foo)).*?(?=bar$|$)

or, if you want to allow foo and/or bar at the beginning and at the end, then with

(?:^|(?<=^foo)|(?<=^bar)).*?(?=foo$|bar$|$)

having result in Groups[0]

Ωmega
  • 42,614
  • 34
  • 134
  • 203
  • This replaces only the foo at the beginning, not for example a bar at the beginning and the replacing at the end doesnt work. – Tearsdontfalls Oct 30 '12 at 20:15
  • @Tearsdontfalls - I see no such example in your question... I have updated my answer with that alternative. – Ωmega Oct 30 '12 at 20:16
  • Ok, i explained it maybe a little bad, with your updated regex it only replaces foo|bar at the end. – Tearsdontfalls Oct 30 '12 at 20:22
  • @Tearsdontfalls - You must have some typo in your code, as my updated answer/solution should work properly. Check your code... – Ωmega Oct 30 '12 at 20:23