【问题标题】:Taking out the last characther from the string, storing it into the variable and then deleting it using Regex C#从字符串中取出最后一个字符,将其存储到变量中,然后使用 Regex C# 将其删除
【发布时间】:2016-10-24 21:01:41
【问题描述】:

我有一个如下字符串(例如):

   Testing stackoverflow 6
   Testing stackoverflow 67
   Testing stackoverflow 687
   Testing stackoverflow 6789

现在我知道一个事实,每次字符串都会以一个数字值结束。我需要取出这个数字...它可以是 1 到 5000 之间的任何数字...我认为使用 lambda 表达式无济于事,因为我无法确定这个数字有多大,所以我想通的正则表达式可能是解决这个问题的好方法,但是如何呢?

编辑:

当我从正则表达式中取出数字并像这样存储时:

int somevalue = Convert.ToInt32(whatever regex takes out);
// Now I have to remove the number from the string...

有人知道吗?

【问题讨论】:

    标签: c# asp.net regex string


    【解决方案1】:
    var match = Regex.Match(myString, @"\d+$");
    if(match != null) {
        long ret;
        long.TryParse(match.Groups[0].Value, out ret);
        myString = Regex.Replace(myString, @"\d+$", "");
    }
    

    只有当字符串末尾有一个数字并且将 ret 声明为 long 时,正则表达式才匹配允许您覆盖 ret 长于 int.MaxValue 的情况

    【讨论】:

    • 好的,一旦我得到实际数字,如何从字符串中删除数字? :)
    • 现在它也将数字替换为 string.Empty
    • 它说不能将 [] 索引应用于“匹配”类型的表达式...有什么想法吗?
    • 我是个白痴,对不起。再次编辑。 match 是一个包含 Group 列表的对象,其中存储了匹配项
    【解决方案2】:
    int number = 0;
    string test = "Testing stackoverflow 6789";
    string[] testArr = test.Split(' ');
    
    int.TryParse(testArr[testArr.Length - 1], out number);
    
    //you have the value in the number variable.
    

    【讨论】:

    • 无论号码多长,这是否有效?可以是3-4-5位吗?取出数字后如何从字符串中删除数字
    • @User987 是的,不管号码多长。您可以轻松地对其进行测试。
    • 好的,这很好用。我喜欢它,我取出号码后如何立即从字符串中删除号码? :D
    • @User987 我不明白你的意思。你在 number 变量中有你的号码,之后你可以随心所欲地使用它。如果问题帮助您将其标记为正确。
    【解决方案3】:
    string str = "Testing stackoverflow 6";
    long value = 0;
    bool b = long.TryParse(str.Split(' ').Last(), out value);
    

    在 Space 的基础上进行拆分,获取 Last 字符串并将其转换为 long 或 int

    【讨论】:

      【解决方案4】:

      使用正则表达式:

      string pattern = @"^.+ (\d+)$";
      string input = "Testing stackoverflow 6789";
      var match = Regex.Match(input, pattern, RegexOptions.None, new TimeSpan(0, 0, 0, 0, 500));
      int? output;
      
      if (match != null)
      {
          string groupValue = match.Groups[1].Value;
          output = Convert.ToInt32(groupValue); 
      }
      

      【讨论】:

      • 嘿,模式不是“测试stackoverflow”...数字之前的文本可以是任何东西,我唯一知道的事实是字符串以数字结尾大声笑
      • 数字前总会有空格吗?我已经更新了。
      • 是的,一旦我得到实际数字,我需要将它从字符串中删除...一旦我获取它,如何从字符串中删除它?
      • 在我的示例中看到 output 变量了吗?这是一个可以为空的 int。只需检查它是否具有 output.HasValue 的值,然后获取该值,如果有,则使用 output.Value
      猜你喜欢
      • 2011-01-19
      • 2021-01-18
      • 2010-11-08
      • 2014-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-19
      相关资源
      最近更新 更多