-4

我需要从现有字符串中提取子字符串。此字符串以无意义的字符(包括“、”“空格”和数字)开头,以“、123”或“、57”或类似数字可以改变的东西结尾。我只需要数字。谢谢

4

5 回答 5

1

正则表达式匹配数字:Regex regex = new Regex(@"\d+");

来源(稍作修改):仅用于数字的正则表达式

于 2013-05-29T13:05:58.147 回答
1
public static void Main(string[] args)
{
    string input = "This is 2 much junk, 123,";
    var match = Regex.Match(input, @"(\d*),$");  // Ends with at least one digit 
                                                 // followed by comma, 
                                                 // grab the digits.
    if(match.Success)
        Console.WriteLine(match.Groups[1]);  // Prints '123'
}
于 2013-05-29T13:14:36.660 回答
0

我想这就是你要找的:

使用正则表达式从字符串中删除所有非数字字符

using System.Text.RegularExpressions;
...
string newString = Regex.Replace(oldString, "[^.0-9]", "");

(如果您不想在最终结果中使用小数分隔符,请从上面的正则表达式中删除 .)。

于 2013-05-29T13:05:19.410 回答
0

您可以使用 \d+ 匹配给定字符串中的所有数字

所以你的代码是

var lst=Regex.Matches(inp,reg)
             .Cast<Match>()
             .Select(x=x.Value);

lst现在包含所有数字


但是,如果您的输入与您的问题中提供的相同,则不需要正则表达式

input.Substring(input.LastIndexOf(", "),input.LastIndexOf(","));
于 2013-05-29T13:06:48.337 回答
0

尝试这样的事情:

String numbers =  new String(yourString.TakeWhile(x => char.IsNumber(x)).ToArray());      
于 2013-05-29T13:08:21.627 回答