kriper
kriper

Reputation: 1054

How can I get a certain segment with regex?

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

enter image description here

How i can get (segment2)? PS: I want to get all of the segments in brackets

Upvotes: 2

Views: 187

Answers (5)

Tim Schmelter
Tim Schmelter

Reputation: 460138

var regex = new Regex(@"\(([^)]*)\)", RegexOptions.Compiled);
string secondMatch = regex.Matches(text).Cast<Match>()
    .Select(m => m.Value.Trim('(', ')'))
    .ElementAtOrDefault(1);

Upvotes: 1

vks
vks

Reputation: 67968

(?<=^[^()]*\([^)]*\)[^()]*\()[^)]*

You can simply use this.See Demo

Upvotes: 1

Rahul Tripathi
Rahul Tripathi

Reputation: 172448

You can try to use this regex:

\(([^)]+)\)

REGEX DEMO

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

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

tafia
tafia

Reputation: 1562

I can't test it but this should probably work:

\([^\)]*\)

Upvotes: 1

Related Questions