【问题标题】:splitting the string and choosing the middle part containing two set of parenthesis [duplicate]拆分字符串并选择包含两组括号的中间部分[重复]
【发布时间】:2016-02-16 14:25:31
【问题描述】:

据我所知,我们使用split 选择字符串的一部分。例如,如果node1.Texttest (delete) if we choose delete

string b1 = node1.Text.Split('(')[0];

那意味着我们选择了test,但是如果我想从node1.Text中选择delete怎么办?

更新:

另一个问题是,当字符串中有两组括号时,如何瞄准delete?。例如字符串是test(2) (delete) - if we choose delete

【问题讨论】:

    标签: c# .net string winforms


    【解决方案1】:

    你也可以使用正则表达式,然后去掉括号:

    resultString = Regex.Match(yourString, @"\((.*?)\)").Value.
                   Replace("(", "").Replace(")", "");
    

    或者更好:

    Regex.Match(yourString, @"\((.*?)\)").Groups[1].Value;
    

    如果要提取括号中的多个字符串:

    List<string> matches = new List<string>();
    var result = Regex.Matches(yourString, @"\((.*?)\)");
    foreach(Match x in result)
          matches.Add(x.Groups[1].Value.ToString());
    

    【讨论】:

    • 为什么不用Regex.Match(yourString, @"\((.*?)\)").Groups[1].Value,那你就不用去掉括号了?
    • @juharr 你说得对,我编辑了我的答案。
    • 非常感谢您的回答。但是如果我们有两个括号呢?
    • @SaberJalilzadeh 看看我编辑的答案。
    • 非常感谢。我会选择你的答案作为接受,但它已经被标记为重复(!!??)
    【解决方案2】:

    如果你的字符串是always xxx(yyy)zzz 格式,你可以添加) 字符,然后拆分它并得到第二个类似的项目;

    var s = "test (delete) if we choose delete";
    string b1 = s.Split(new[] { '(', ')' })[1];
    

    【讨论】:

    • 请看我的更新。
    【解决方案3】:
    string tmp = node1.Text.Split('(')[1];
    string final = tmp.Split(')')[0];
    

    也是可以的。

    使用索引[x],您可以针对拆分原始字符串的字符之前和之后的字符串部分。如果字符出现多次,则生成的字符串包含更多部分。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多