Reputation: 1054
I have a simple string
testteststete(segment1)tete(segment2)sttes323testte(segment3)eteste
I need to get (segment2). Each segment may be any text. I tried to use this regex
\(.+\)
. But i get this result
How i can get (segment2)? PS: I want to get all of the segments in brackets
Upvotes: 2
Views: 187
Reputation: 460138
var regex = new Regex(@"\(([^)]*)\)", RegexOptions.Compiled);
string secondMatch = regex.Matches(text).Cast<Match>()
.Select(m => m.Value.Trim('(', ')'))
.ElementAtOrDefault(1);
Upvotes: 1
Reputation: 626861
In C#, you can just match all the (...)
substrings and then access the second one using Index 1:
var rx = @"\([^)]*\)";
var matches = Regex.Matches(str, rx).Cast<Match>().Select(p => p.Value).ToList();
var result = matches != null && matches.Count > 1 ? matches[1] : string.Empty;
See IDEONE demo
The regex matches
\(
- an opening (
[^)]*
- 0 or more characters other than )
\)
- a closing )
.Upvotes: 2