0

我目前正在尝试对 JSON 字符串进行正则表达式替换,如下所示:

String input = "{\"`####`Answer_Options11\": \"monkey22\",\"`####`Answer_Options\": \"monkey\",\"Answer_Options2\": \"not a monkey\"}";

a 目标是查找并替换所有关键字段以`####`开头的值字段

我目前有这个:

static Regex _FieldRegex = new Regex(@"`####`\w+" + ".:.\"(.*)\",");

static public string MatchKey(string input)
{
    MatchCollection match = _encryptedFieldRegex.Matches(input.ToLower());
    string match2 = "";
    foreach (Match k in match )
    {
        foreach (Capture cap in k.Captures)
        {
            Console.WriteLine("" + cap.Value);
            match2 = Regex.Replace(input.ToLower(), cap.Value.ToString(), @"CAKE");
        }
    }

    return match2.ToString();
}

现在这行不通了。我自然猜想,因为它会选择整个 `####`Answer_Options11\": \"monkey22\",\"`####`Answer_Options\": \"monkey\" 作为匹配项并替换它。我只想替换match.Group[1]字符串上的单个匹配项。

归根结底,JSON 字符串需要看起来像这样:

String input = "{\"`####`Answer_Options11\": \"CATS AND CAKE\",\"`####`Answer_Options\": \"CAKE WAS A LIE\",\"Answer_Options2\": \"not a monkey\"}";

知道怎么做吗?

4

2 回答 2

2

你想要一个积极的前瞻和积极的后瞻:

(?<=####.+?:).*?(?=,)

前瞻和后瞻将验证它是否匹配这些模式,但不会将它们包含在匹配中。这个网站很好地解释了这个概念。

从 RegexHero.com 生成的代码:

string strRegex = @"(?<=####.+?:).*?(?=,)";
Regex myRegex = new Regex(strRegex);
string strTargetString = @" ""{\""`####`Answer_Options11\"": \""monkey22\"",\""`####`Answer_Options\"": \""monkey\"",\""Answer_Options2\"": \""not a monkey\""}""";

foreach (Match myMatch in myRegex.Matches(strTargetString))
{
  if (myMatch.Success)
  {
     // Add your code here
  }
}

这将匹配"monkey22""monkey"但不匹配"not a monkey"

于 2013-10-22T13:04:41.137 回答
0

根据@Jonesy的回答,我得到了这个适合我想要的东西。它包括我需要的组上的 .Replace。前后负面的看法非常有趣,但我需要替换其中的一些值,因此需要替换组。

    static public string MatchKey(string input)
    {

       string strRegex = @"(__u__)(.+?:\s*)""(.*)""(,|})*";
        Regex myRegex = new Regex(strRegex, RegexOptions.IgnoreCase | RegexOptions.Multiline);
        IQS_Encryption.Encryption enc = new Encryption();

        int count = 1;

        string addedJson = "";

        int matchCount = 0;
        foreach (Match myMatch in myRegex.Matches(input))
        {

            if (myMatch.Success)
            {
                //Console.WriteLine("REGEX MYMATCH: " + myMatch.Value);
                input = input.Replace(myMatch.Value, "__e__" + myMatch.Groups[2].Value + "\"c" +  count + "\"" + myMatch.Groups[4].Value);
                addedJson += "c"+count + "{" +enc.EncryptString(myMatch.Groups[3].Value, Encoding.UTF8.GetBytes("12345678912365478912365478965412"))+"},";
            }

            count++;
            matchCount++;
        }
        Console.WriteLine("MAC" + matchCount);
        return input + addedJson;
    }`

再次感谢@Jonesy的巨大帮助。

于 2013-10-23T14:47:41.490 回答