简体   繁体   English

使用Regex C#解析字符串

[英]Parse String with Regex c#

I am trying to customise a DevExpress grid filter. 我正在尝试自定义DevExpress网格过滤器。

Currently I return the data from my api, and so I need to parse the built in string which is returned from the grid. 当前,我从api返回数据,因此我需要解析从网格返回的内置字符串。

An example of the filter string is; 过滤器字符串的一个示例是;

StartsWith([name], 'test') And StartsWith([quantity], '12') And StartsWith([id], '1') And StartsWith([date], '01/10/2015') StartsWith([name],'test')和StartsWith([quantity],'12')And StartsWith([id],'1')And StartsWith([date],'01 / 10/2015')

I would like to convert this to a Dictionary in the most efficient way? 我想以最有效的方式将其转换为字典吗?

You could use Regex for filtering the key/value pair outta your string and a simple foreach to prepare the dictionary. 您可以使用Regex过滤掉字符串中的键/值对,并使用简单的foreach来准备字典。

This could be a solution: 这可能是一个解决方案:

public static Dictionary<string, object> FilterAPIData(string data)
    {
        var r = new Regex(@"\[\w+\], \'[\w/]+\'");

        var result = r.Matches(data);
        var dict = new Dictionary<string, object>();

        foreach (Match item in result)
        {
            var val = item.Value.Split(',');
            dict.Add(val[0], val[1]);
        }

        return dict;
    }

Regex might be the best option for this, but I'll show you how to do it without Regex as it can be a bit difficult to understand. 正则表达式可能是最好的选择,但是我将向您展示如何不使用正则表达式,因为它可能有点难以理解。

Assuming your string will always be in this format you can do this: 假设您的字符串将始终采用这种格式,则可以执行以下操作:

string str = "StartsWith([name], 'test') And StartsWith([quantity], '12') And StartsWith([id], '1') And StartsWith([date], '01/10/2015')";
var strArray = str.Split(new string[]{"And "}, StringSplitOptions.None);

var dict = new Dictionary<string, string>();
foreach(var value in strArray)
{
    dict.Add(GetStringBetween(value, "[", "]"), GetStringBetween(value, "'", "'"));
}

private string GetStringBetween(string value, string startDelim, string endDelim)
{
     int first = value.IndexOf(startDelim) + startDelim.Length;
     int last = value.LastIndexOf(endDelim);

     return value.Substring(first, last - first);
}

//Output : 
//name test 
//quantity 12 
//id 1 
// date 01/10/2015 

If there other formats the string can be in you can adjust as needed. 如果还有其他格式的字符串,则可以根据需要进行调整。 I would also consider adding in more validation/error handling, but I will let you figure that out ;) 我也将考虑增加更多的验证/错误处理,但是我会让你知道;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM