Regex Quantifier on Alternatives(vertical bar “|”)
-
21-07-2021 - |
Question
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.
Solution
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;
OTHER TIPS
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]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow