简体   繁体   English

我怎样才能获得正则表达式的某个细分?

[英]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). 我需要获取(segment2)。 Each segment may be any text. 每个段可以是任何文本。 I tried to use this regex \\(.+\\) . 我试图使用此正则表达式\\(.+\\) But i get this result 但是我得到这个结果

在此处输入图片说明

How i can get (segment2)? 我如何获得(segment2)? PS: I want to get all of the segments in brackets PS:我想将所有细分都放在方括号中

In C#, you can just match all the (...) substrings and then access the second one using Index 1: 在C#中,您可以只匹配所有(...)子字符串,然后使用索引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 IDEONE演示

The regex matches 正则表达式匹配

  • \\( - an opening ( \\( -开头(
  • [^)]* - 0 or more characters other than ) [^)]* -比其他0个或更多字符)
  • \\) - 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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