Convert string in array format into an array and retrieve values

Asked

Viewed 72 times

1

In the database I have a TEXT where an array is saved in this format:

[ 
    [ resumo: null ] 
    [ datainicio: 2015-09-17T00:00:00.000-0300 ] 
    [ datafim: 2015-09-22T00:00:00.000-0300 ] 
    [ equipamento: 3421 ] 
]

I need to retrieve the values of the start date and date. How could I do this? I was researching about the split function of Java, but I could not use it in the right way to bring me the result.

2 answers

2


Follows:


public static void main(String[] args)
    {
        String str = "[[ resumo: null ] [ datainicio: 2015-09-17T00:00:00.000-0300 ] [ datafim: 2015-09-22T00:00:00.000-0300 ] [ equipamento: 3421 ]]"
                .replaceAll(Pattern.quote("[["), "")    
                .replaceAll(Pattern.quote("]]"), "");

        String[] strArray = str.split(Pattern.quote("] ["));
        for (int i = 0; i menor strArray.length; i++)
            strArray[i] = strArray[i].replaceAll(Pattern.quote("] ["), "");

        for (String string : strArray)
            System.out.println(string);
    }
  • Thank you Emir! That’s just what I needed! Made some treatments, was perfect!

1

Make sure that’s what you want:

(This code hasn’t been tested, but you might have some idea how to do it)

String frase = "[ 
    [ resumo: null ] 
    [ datainicio: 2015-09-17T00:00:00.000-0300 ] 
    [ datafim: 2015-09-22T00:00:00.000-0300 ] 
    [ equipamento: 3421 ] 
]";  
Pattern p = Pattern.compile("datainicio: (.*?) ]"); 
// para os outros casos deves de criar um Pattern idêntico  
// Pattern p = Pattern.compile("datafim: (.*?) ]"); 
// Pattern p = Pattern.compile("equipamento: (.*?) ]"); 

Matcher m = p.matcher(frase);  

while (m.find()) {  
    // chamada diferente:  
    System.out.println(m.group(1));  
} 

Here’s some more information on this

  • 1

    Thanks friend! I did not know this form! I managed to use it, but in case I need to recover other fields, or all fields, I thought I’d use the one that Emir Marques posted! Anyway, thank you! Hug!

Browser other questions tagged

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