从字符串中解析int的更好方法

Mig*_*uel 0 c# string string-parsing

我试图看看是否有一种不同的/更好的方法来解析我拥有的字符串.

字符串是"#def xyz [timer = 50,fill = 10]".从这个字符串我试图检索计时器和填充值.

我目前的代码是:

string def = "#def xyz[timer=50, fill=10]";
string _timer = def.Remove(def.IndexOf(","));
_timer = _timer.Remove(0, _timer.IndexOf("=", _timer.IndexOf("timer")) + 1);

string _fill = def.Remove(def.IndexOf("]"));
_fill = _fill.Remove(0, _fill.IndexOf("=", _fill.IndexOf("fill")) + 1);

int timer = Int32.Parse(_timer);
int fill = Int32.Parse(_fill);
Run Code Online (Sandbox Code Playgroud)

有什么建议?

提前致谢!

Jon*_*eet 6

我可能会使用正则表达式.例如:

using System;
using System.Text.RegularExpressions;

class Test
{
    static void Main()
    {
        // You can create the regex once and reuse it, of course. Adjust
        // as necessary if the name isn't always "xyz" for example.
        Regex regex = new Regex(@"^#def xyz\[timer=(\d+), fill=(\d+)\]$");
        string input = "#def xyz[timer=50, fill=10]";
        Match match = regex.Match(input);
        if (match.Success)
        {
            int fill = int.Parse(match.Groups[1].Value);
            int timer = int.Parse(match.Groups[2].Value);
            Console.WriteLine("Fill={0}, timer={1}", fill, timer);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

笔记:

  • 这只涉及非负整数
  • 如果值超出范围,它将失败(例外) int

我会说这表明你做的比那些Remove电话更清楚......