views:

595

answers:

3

I'm looking for a method to assign variables with patterns in regular expressions with C++ .NET something like

String^ speed; String^ size;

"command SPEED=[speed] SIZE=[size]"

Right now I'm using IndexOf() and Substring() but it is quite ugly

A: 

If you put all the variables in a class, you can use reflection to iterate over its fields, getting their names and values and plugging them into a string.

Given an instance of some class named InputArgs:

foreach (FieldInfo f in typeof(InputArgs).GetFields()) {
    string = Regex.replace("\\[" + f.Name + "\\]",
        f.GetValue(InputArgs).ToString());
}
+2  A: 
String^ speed; String^ size;
Match m;
Regex theregex = new Regex (
  "SPEED=(?<speed>(.*?)) SIZE=(?<size>(.*?)) ",
  RegexOptions::ExplicitCapture);
m = theregex.Match (yourinputstring);
if (m.Success)
{
  if (m.Groups["speed"].Success)
    speed = m.Groups["speed"].Value;
  if (m.Groups["size"].Success)
    size = m.Groups["size"].Value;
}
else
  throw new FormatException ("Input options not recognized");

Apologies for syntax errors, I don't have a compiler to test with right now.

Sparr
+2  A: 

If I understand your question correctly, you are looking for capturing groups. I'm not familiar with the .net api, but in java this would look something like:

Pattern pattern = Pattern.compile("command SPEED=(\d+) SIZE=(\d+)");
Matcher matcher = pattern.matcher(inputStr);
if (matcher.find()) {
  speed = matcher.group(1);
  size = matcher.group(2);
}

There are two capturing groups in the regex pattern above, designated by the two sets of parentheses. In java these must be referenced by number but in some other languages you are able to reference them by name.

jon