How do I get a value between brackets in the string?

2

I have a string that will vary the values, I need to get the values inside the [],

{"time_zones":[]}

In case it would be empty, it could be filled:

{"time_zones":[teste]}

I'm trying to do this

 var palavras = a.Split('[');
 var palavra = palavras[1];

But it returns me the rest of the code: ]} In case if there was nothing, the value was empty, if it was filled I needed the test. (this value varies);

    
asked by anonymous 13.06.2018 / 21:24

2 answers

5

You can do this with REGEX "\[(.*)\]"

  • \[ Escape is required to be treated as text and not as a set.
  • .* Look for any or several occurrences.
  • No C# get the first group, it will be where the word teste (shown in the second example) or whatever is between the brackets.

Running on dotnetfiddle

>
 using System;
    using static System.Console;
    using System.Text.RegularExpressions;                       
        public class Program {
            public static void Main() {
                string texto = "{\"time_zones\":[teste]}";
                Regex rgx = new Regex(@"\[(.*)\]");
                Console.Write(rgx.Match(texto).Groups[1]);
            }
        }
    
13.06.2018 / 21:37
1

Within a controller method,

public string GetMinhaString()
{
    string tuaString = @"{ ""time_zones"": [ ""teste"", ""zero"", ""um"" ] }";

    var o = JsonConvert.DeserializeObject<MeuObjeto>(tuaString);

    return string.Join("-", o.time_zones) + ", total de " + o.time_zones.Length ;
} 

and declares a private class within the controller as follows,

private class MeuObjeto
{
    public string[] time_zones { get; set; }
}

In this way, you will get the information you need and type according to the provided JSON.

    
13.06.2018 / 23:53