用正则表达式分配变量

时间:2020-03-06 14:24:22  来源:igfitidea点击:

我正在寻找一种使用C ++ .NET在正则表达式中分配带有模式的变量的方法
就像是

String^ speed;
String^ size;

"命令SPEED = [速度] SIZE = [大小]"

现在我正在使用IndexOf()和Substring(),但是非常难看

解决方案

如果将所有变量放在类中,则可以使用反射来遍历其字段,获取它们的名称和值并将其插入字符串中。

给定一个名为InputArgs的类的实例:

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

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

抱歉出现语法错误,我现在没有要测试的编译器。

如果我正确理解问题,那么我们正在寻找捕获群体。我不熟悉.net api,但是在Java中,它看起来像:

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

上面的正则表达式模式中有两个捕获组,由两组括号指定。在Java中,这些必须按数字引用,但是在某些其他语言中,我们也可以按名称引用。