获取字符串的数字部分

本文关键字:数字部 字符串 获取 | 更新日期: 2023-09-27 18:30:54

我有一个像"1000/Refuse5.jpg"或"50/Refuse5.jpeg"这样的字符串。请注意,在本例中,字符串的第一部分为 1000 或 50 是变量。我想通过 C# 方法从这个字符串中获取"5"号。有人可以帮助我吗?

获取字符串的数字部分

您可以使用正则表达式

string input = "1000/Refuse5.jpg";
var num = Regex.Matches(input, @"'d+").Cast<Match>().Last().Value;
一个

更受约束的正则表达式。

var fileName = "1000/Refuse5.jpg";
var match = Regex.Match(fileName, @"(?<='D+)('d+)(?='.)");
if(match.Success)
{
    var value = int.Parse(match.Value);
}

一个更干净的正则表达式:

Console.WriteLine (Regex.Match("123ABC5", @"'d", RegexOptions.RightToLeft).Value); // 5

请注意,如果最后一个数字将超过一位数字,请改用'd+

您可以使用正则表达式提取字符串的相关部分,然后将其转换为整数。您需要研究您的输入集,并确保您使用的正则表达式符合您的需求。

        string input = "1234/Refuse123.jpg";
        // Look for any non / characters until you hit a /
        // then match any characters other than digits as many
        // as possible. After that, match digits as many as possible
        // and capture them in a group (hence the paranthesis). And 
        // finally match everything else at the end of the string
        Regex regex = new Regex("[^/]*/[^''d]*([''d]*).*");
        var match = regex.Match(input);
        // Group 0 will be the input string
        // Group 1 will be the captured numbers
        Console.WriteLine(match.Groups[1]);