Home > database >  Problem with string (string contains brace characters and a plus sign)
Problem with string (string contains brace characters and a plus sign)

Time:01-28

I have a problem with regex. The variable media.Value may contain the characters "() " which causes an error in the regex and prevents it from working.

My code

Match renderMatch = Regex.Match(mediaMatch.Groups[0].Value, "(?<=\"name\":\""   media.Value   "\",\"render\":).*?(?=,)");
Match mutedMatch = Regex.Match(mediaMatch.Groups[0].Value, "(?<=\"muted\":).*?(?=,\"name\":\""   media.Value   "\")");

json I work with

[{"alignment":5,"cx":844.0,"cy":264.0,"id":4,"locked":false,"muted":false,"name":"Text (GDI  )","render":true,"source_cx":844,"source_cy":264,"type":"text_gdiplus_v2","volume":1.0,"x":549.0,"y":383.0},{"alignment":5,"cx":1920.0,"cy":1080.0,"id":3,"locked":false,"muted":false,"name":"Color","render":true,"source_cx":1920,"source_cy":1080,"type":"color_source_v3","volume":1.0,"x":0.0,"y":0.0}]

As long as there are no "()" in the name field everything works. For example:

Working

"muted":false,"name":"Color","render":true

Not working

"muted":false,"name":"Text (GDI  )","render":true

The question is. Is there any regex option that would ignore the () in string, or how else could I get an output like this:

"Text \(GDI \ \)"

CodePudding user response:

You can deserialize your JSON string to strongly typed models and then gather your required fields

An example with your JSON string is: https://dotnetfiddle.net/cqkOdu

using System;
using System.Collections.Generic;
using Newtonsoft.Json;
                    
public class Program
{
    public static void Main()
    {
        var myJsonResponse= @"[{'alignment':5,'cx':844.0,'cy':264.0,'id':4,'locked':false,'muted':false,'name':'Text (GDI  )','render':true,'source_cx':844,'source_cy':264,'type':'text_gdiplus_v2','volume':1.0,'x':549.0,'y':383.0},{'alignment':5,'cx':1920.0,'cy':1080.0,'id':3,'locked':false,'muted':false,'name':'Color','render':true,'source_cx':1920,'source_cy':1080,'type':'color_source_v3','volume':1.0,'x':0.0,'y':0.0}]";
        List<Root> myDeserializedClass = JsonConvert.DeserializeObject<List<Root>>(myJsonResponse);
        foreach(var item in myDeserializedClass)
        {
            Console.WriteLine(item.name);
        }
    }
}

    public class Root
    {
        public int alignment { get; set; }
        public double cx { get; set; }
        public double cy { get; set; }
        public int id { get; set; }
        public bool locked { get; set; }
        public bool muted { get; set; }
        public string name { get; set; }
        public bool render { get; set; }
        public int source_cx { get; set; }
        public int source_cy { get; set; }
        public string type { get; set; }
        public double volume { get; set; }
        public double x { get; set; }
        public double y { get; set; }
    }
  •  Tags:  
  • Related