0

I'm trying to see if there is a different/better way of parsing a string that I have.

The string is "#def xyz[timer=50, fill=10]". From this string I am trying to retrieve the timer and fill values.

The code I currently have is:

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);

Any suggestions?

Thanks in advance!

3
  • 2
    Have you tried regular expression? Commented Jan 2, 2013 at 19:56
  • 6
    What do you mean by better? Easier to read? More performant? Commented Jan 2, 2013 at 19:57
  • k0stya, platon No, I haven't tried regular expressions yet. System Down Yeah something with better performance. The def string can get a bit longer than what I have. Commented Jan 2, 2013 at 20:03

3 Answers 3

6

I would probably use a regular expression. For example:

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);
        }
    }
}

Notes:

  • This only deals with non-negative integers
  • It will fail (with an exception) if the value is out of range for an int

I'd say it indicates what you're doing more clearly than those Remove calls though...

Sign up to request clarification or add additional context in comments.

Comments

1
      Match m = Regex.Match("#def xyz[timer=50, fill=10]", "timer=([0-9]+?), fill=([0-9]+?)[]]");

      string timer = m.Result("$1");
      string fill = m.Result("$2");

Comments

0

I like using split when I can, it is much faster than regex in most cases -- I didn't test but I expect it would be faster here. Of course there is very little error checking in this code.

void Main()
{
  string def = "#def xyz[timer=50, fill=10]";

  string [] inBracket = def.Split("[]".ToCharArray());

  string [] elements = inBracket[1].Split(",".ToCharArray());

  int timer = int.Parse(elements[0].Split("=".ToCharArray())[1]);

  int fill = int.Parse(elements[1].Split("=".ToCharArray())[1]);

  Console.WriteLine("timer = "+timer.ToString());
  Console.WriteLine("fill = "+fill.ToString());

}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.