Assigning variables with regex

I am looking for a method for assigning variables with patterns in regular expressions using C ++. NET something like

String^ speed;
String^ size;

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

Right now I'm using IndexOf () and Substring (), but it's pretty ugly

+3
source share
3 answers
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");

I apologize for syntax errors, I do not have a compiler for testing right now.

+3
source

If I understand your question correctly, you are looking for groups to capture. I am not familiar with the .net api, but in java it looks something like this:

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 capture groups in the above regex pattern, indicated by two brackets. In java, they should be referenced by a number, but in some other languages ​​you can refer to them by name.

+2

If you put all the variables in a class, you can use reflection to iterate over your fields, get their names and values, and include them in the string.

Given an instance of some class called InputArgs:

foreach (FieldInfo f in typeof(InputArgs).GetFields()) {
    string = Regex.replace("\\[" + f.Name + "\\]",
        f.GetValue(InputArgs).ToString());
}
0
source

Source: https://habr.com/ru/post/1697181/


All Articles