How to pick a value between brackets in the string?

Asked

Viewed 660 times

3

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 may be filled:

{"time_zones":[teste]}

I’m trying to do it like this

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

But he 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);

  • 3

    You can do so... but if your string is an deseralizable as it seems, there are other approaches to it

  • Can solve @Leandroangelo, thanks.

  • 1

    Treating as string or Json?

  • String, I made this string[] split = a.Split(new char[] { '[', ']' }); Messagebox.Show(split[1]);

  • Would you accept a Regex? you’re trying to get the word test?

  • Yes I need to pick up the word test, but will not always have this word, including can contain other characters, and several words.

  • @marianac_costa added regex to your question, you said it could be :)

  • 3

    treats as json that is best....

  • 2

    Definitely the @Rovannlinhalis comment is the following line. This is a json, treat it as such will make life easier. It is not worth the trouble to envision a solution of this kind, maintenance will charge expensive.

  • 1

    There will come a time {"time_zones":[teste, teste2]} to mess up the midfield (=C

Show 5 more comments

2 answers

5


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

  • \[ Escape is necessary to be treated as text and not as a set.
  • .* Look for any or several occurrences.
  • In the C# take the first Group, that’s where the word teste(demonstrated in the second example) or anything between 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]);
            }
        }

1

Within a controller method, it does

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; }
}

This way you will get the information you need and typed according to the JSON provided.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.