문제

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.

도움이 되었습니까?

해결책

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;

다른 팁

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]

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top