[英]How to build a command parser with regex
I'm trying to implement a command parser to parse command parameters to a key value pair list. 我正在尝试实现命令解析器,以将命令参数解析为键值对列表。 For example, there is a command to output images:
[name]_w[width]_h[height]_t[transparency]
,say"image01_w64_h128_t90",the program would output the image "image01" with specified size and transparency, and so far I'm using regex to solve it. 例如,有一个输出图像的命令:
[name]_w[width]_h[height]_t[transparency]
,例如“ image01_w64_h128_t90”,程序将以指定的大小和透明度输出图像“ image01”。我正在使用正则表达式来解决它。
Code: 码:
private static readonly Regex CommandReg = new Regex(
@"^(?<name>[\d\w]+?)(_W(?<width>\d+))?(_H(?<height>\d+))?(_T(?<transparency>\d+))?$"
, RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.ExplicitCapture);
public static NameValueCollection ParseCommand(string command)
{
var match = CommandReg.Match(command);
if (!match.Success) return null;
var groups = match.Groups;
var paramList = new NameValueCollection(4);
paramList["name"] = groups["name"].Value;
paramList["width"] = groups["width"].Value;
paramList["height"] = groups["height"].Value;
paramList["transparency"] = groups["transparency"].Value;
return paramList;
}
This way worked and the code is very easy. 这种方式有效,并且代码非常简单。 However, a higher demand is if the order of parameters is changed, say "image01_h128_w64_t90" or "image01_t90_w64_h128", the program can also output expected result.
但是,更高的要求是如果更改参数的顺序(例如“ image01_h128_w64_t90”或“ image01_t90_w64_h128”),程序也可以输出预期结果。
Thanks for any suggestion, editing, and viewing. 感谢您的任何建议,编辑和查看。
Just do string.split('_')
then iterate through the array to find everything you need. 只需执行
string.split('_')
然后遍历数组以查找所需的所有内容。
if(arr[i].startswith("w"))
{
paramList["width"] = arr[i].remove(0,1);
}
and so on. 等等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.