Regex剪切字符串c#中的数字

本文关键字:数字 字符串 Regex | 更新日期: 2023-09-27 17:58:11

我有一个字符串如下2 - 5,现在我想用Regex C#得到数字5(我是Regex的新手),你能给我一个主意吗?感谢

Regex剪切字符串c#中的数字

您可以简单地使用String.Split方法:

int number = int.Parse("2 - 5".Split('-', ' ').Last());

如果最后一个数字后面没有空格,这将起作用。如果是这样的话:

 int number = int.Parse("2 - 5  ".Split('-', ' ')
              .Last(x => x.Any() && x.All(char.IsDigit)));

非常简单地如下:

''s-'s('d)'

并提取第一匹配组

@SShashank拥有它的权利,但我想我应该提供一些代码,因为你提到你是Regex:的新手

string s = "something 2-5 another";
Regex rx = new Regex(@"-('d)");
if (rx.IsMatch(s))
{
    Match m = rx.Match(s);
    System.Console.WriteLine("First match: " + m.Groups[1].Value);
}

Groups[0]是整个匹配,Groups[1]是第一个匹配的组(填充在parens中)。

如果你真的想使用regex,你可以简单地执行:

string text = "2 - 5";
string found = Regex.Match(text, @"'d+", RegexOptions.RightToLeft).Value;