如何在这样一个简单的字符串中单独获取整数和字符?

pen*_*ake 3 .net c# regex string parsing

我有一些字符串:"7d","5m","95d"等.

我需要找到简单的方法来分别获得整数和char.

我怎样才能做到这一点:

int number = GetNumber("95d"); //should return 95
char code = GetCode("95d"); // should return d
Run Code Online (Sandbox Code Playgroud)

Joe*_*Joe 5

这些是表达式:

[^\d]+ <- not digit
\d+ <- digits
Run Code Online (Sandbox Code Playgroud)


编辑

    static int GetNumber(string text)
    {
        string pat = @"\d+";
        int output;
        // Instantiate the regular expression object.
        Regex r = new Regex(pat, RegexOptions.IgnoreCase);
        Match m = r.Match(text);
        if (int.TryParse(m.Value, out output))
            return output;
        else
            return int.MinValue; // something unlikely
    }

    static char GetChar(string text)
    {
        string pat = @"[^\d]";
        int output;
        // Instantiate the regular expression object.
        Regex r = new Regex(pat, RegexOptions.IgnoreCase);
        Match m = r.Match(text);
        return m.Value.Length == 1 ? m.Value[0] : '\0';
    }
Run Code Online (Sandbox Code Playgroud)

您实际上只需要创建RegExp一次该对象,而不是每次方法调用.

  • 用户如何捕获这些表达式匹配的值? (2认同)