【问题标题】:Get the substring of the non conditional part获取非条件部分的子串
【发布时间】:2018-09-14 05:10:24
【问题描述】:

我有这个字符串,例如:
2X+4+(2+2X+4X) +4
括号的位置可以变化。我想知道如何在没有括号的情况下提取部分。例如我想要2X+4+4。有什么建议么? 我正在使用 C#。

【问题讨论】:

  • @Aldert 这是一个 C# 问题,如何让它成为一个 javascript 问题的副本?请删除您的标志
  • @Shahrier,这是因为我正在为您寻找一个好的解决方案,这将是正则表达式,尤其是当您在 perenthises 中有括号时。我什至没有看语言。
  • 如果你只是去掉括号,你会得到2X+4++4。我是否正确,您只想要两个 4 之间的 1 加?如果不是加号而是其他运算符怎么办?
  • 如果你有2X+4+(2+2X+(3X+7X)+4X)+4会发生什么?有可能得到吗?

标签: c# substring


【解决方案1】:

尝试如下简单的字符串索引和子字符串操作:

string s = "2X+4+(2+2X+4X)+4";

int beginIndex = s.IndexOf("(");
int endIndex = s.IndexOf(")");

string firstPart = s.Substring(0,beginIndex-1);
string secondPart = s.Substring(endIndex+1,s.Length-endIndex-1);

var result = firstPart + secondPart;

解释:

  1. 获取(的第一个索引
  2. 获取)的第一个索引
  3. 创建两个子字符串,第一个是beginIndex之前的1个索引以删除像+这样的数学符号
  4. 第二个是帖子endIndex,直到字符串长度
  5. 连接两个字符串top得到最终结果

【讨论】:

    【解决方案2】:

    试试Regex approach:

    var str = "(1x+2)-2X+4+(2+2X+4X)+4+(3X+3)";
    var regex = new Regex(@"\(\S+?\)\W?");//matches '(1x+2)-', '(2+2X+4X)+', '(3X+3)'
    var result = regex.Replace(str, "");//replaces parts above by blank strings: '2X+4+4+'
    result = new Regex(@"\W$").Replace(result, "");//replaces last operation '2X+4+4+', if needed
    //2X+4+4                                                                        ^
    

    【讨论】:

    • 您能分享一下为什么这个正则表达式有效吗?或者也许分享一些链接来了解正则表达式模式?谢谢
    • 这将在 "2X+4+(2+2X+4X)+4+(3X+3)" 上失败。
    • 我同意,这种使用正则表达式的方法更简洁
    • @Enigmativity,你的情况已经解决了
    【解决方案3】:

    试试这个:

    var str = "(7X+2)+2X+4+(2+2X+(3X+3)+4X)+4+(3X+3)";
    
    var result =                                           
        str
            .Aggregate(
                new { Result = "", depth = 0 },
                (a, x) => 
                    new
                    {
                        Result = a.depth == 0 && x != '(' ? a.Result + x : a.Result,
                        depth = a.depth + (x == '(' ? 1 : (x == ')' ? -1 : 0))
                    })
            .Result
            .Trim('+')
            .Replace("++", "+");
    
    //result == "2X+4+4"
    

    这处理嵌套、前导和尾随括号。

    【讨论】:

      猜你喜欢
      • 2022-01-02
      • 2018-07-15
      • 1970-01-01
      • 2014-02-10
      • 2013-06-13
      • 1970-01-01
      • 2015-02-27
      • 2023-03-05
      • 2015-12-29
      相关资源
      最近更新 更多