c# - 在正则表达式匹配/替换模式上需要一些帮助

标签 c# regex

我的最终目标是将以下字符串转换为 JSON,但我会满足于通过将字段名与每个值组合起来让我更接近一步。

示例数据:

Field1:abc;def;Field2:asd;fgh;

使用 Regex.Replace(),我需要它至少看起来像这样:

Field1:abc,Field1:def,Field2:asd,Field2:fgh

最终,如果可以通过正则表达式在一次调用中完成,这个结果会很棒。

{"Field1":"abc","Field2":"asd"},{"Field1":"def","Field2":"fgh"}

我已经尝试过这种模式的许多不同变体,但似乎无法做到正确:

(?:(\w+):)*?(?:([^:;]+);)

我能找到的唯一一个例子是在做类似的事情,但差异足够大,我无法完全理解它。

Regex to repeat a capture across a CDL?

EDIT:

这是我的解决方案。我不会将其作为“解决方案”发布,因为我想赞扬其他人发布的解决方案。最后,我从每个已发布的解决方案中取了一个,并提出了这个。感谢所有发布的人。我赞扬了编译、执行速度最快且结果最准确的解决方案。

    string hbi = "Field1:aaa;bbb;ccc;ddd;Field2:111;222;333;444;";

    Regex re = new Regex(@"(\w+):(?:([^:;]+);)+");
    MatchCollection matches = re.Matches(hbi);

    SortedDictionary<string, string> dict = new SortedDictionary<string, string>();

    for (int x = 0; x < matches.Count; x++)
    {
        Match match = matches[x];
        string property = match.Groups[1].Value;

        for (int i = 0; i < match.Groups[2].Captures.Count; i++)
        {
            string key = i.ToString() + x.ToString();
            dict.Add(key, string.Format("\"{0}\":\"{1}\"", property, match.Groups[2].Captures[i].Value));
        }
    }
    Console.WriteLine(string.Join(",", dict.Values));

最佳答案

Now you have two problems

我认为正则表达式不是处理此问题的最佳方式。您可能应该从按分号拆分开始,然后遍历结果以查找以“Field1:”或“Field2:”开头的值,并将结果收集到字典中。

将此视为伪代码,因为我没有编译或测试它:

string[] data = input.Split(';');
dictionary<string, string> map = new dictionary<string, string>();

string currentKey = null;
foreach (string value in data)
{
    // This part should change depending on how the fields are defined.
    // If it's a fixed set you could have an array of fields to search,
    // or you might need to use a regular expression.
    if (value.IndexOf("Field1:") == 0 || value.IndexOf("Field2:"))
    {
        string currentKey = value.Substring(0, value.IndexOf(":"));
        value = value.Substring(currentKey.Length+1);
    }
    map[currentKey] = value;
}
// convert map to json

关于c# - 在正则表达式匹配/替换模式上需要一些帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9380005/

相关文章:

python - 如何在Python中每次运行代码时只创建一个对象

c# - 将 net framework 4.5.2 升级到 4.7.1 后生成错误 "An attempt was made to load an assembly with an incorrect format "

c# - WPF 异步等待任务锁定 UI 线程并行运行任务

c# - Html.CheckBoxFor 类型转换错误

c# - 如何将 IEnumerable<string> 转换为一个逗号分隔的字符串?

Java 正则表达式 : word ending in 's' except specific words

java - Java 中用于正整数的正则表达式(不包括以零开头的整数)

java - 如何处理 Pattern.compile 中的双引号?

php - 在 SELECT 语句中按字符长度匹配

C# JSON 反序列化对象内的对象列表