简体   繁体   中英

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

在此处输入图片说明

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

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 ) .

我无法对其进行测试,但这可能可以工作:

\([^\)]*\)

You can try to use this regex:

\(([^)]+)\)

REGEX DEMO

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

You can simply use this. See Demo

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM