stumpylumpy
stumpylumpy

Reputation: 45

Removing special characters from string

I want to parse this string into a list and return {1.193493, 54.6333, 2.093077, 31.6235, 6.175355, 21.6479}. How do I get rid of the square brackets???? I used a for loop and replace but it doesn't work.

String st = "[[[1.193493,54.6333],[2.093077,31.6235],[6.175355,21.6479]]]"

String[] parsed = st.split(",");

for (String next : parsed) {
        next.replace("//[", "").replace("//]", "");
    }

Upvotes: 0

Views: 199

Answers (4)

radoh
radoh

Reputation: 4809

replace() works with plain Strings, not regex. Therefore you can simply use:

next.replace("[", "").replace("]", "");

Also notice that you need to assign it to some string variable; assigning it to need won't work (won't modify elements in parsed array).

You should actually remove the braces first and split later, like this:

String[] parsed = st.replace("[", "").replace("]", "").split(",");

Upvotes: 1

Quinn
Quinn

Reputation: 4504

You could achieve your goal in two steps.

1) Remove all special characters except comma (,)

2) Then split by comma (,)

public static void main(String[] args) {        
    String st = "[[[1.193493,54.6333],[2.093077,31.6235],[6.175355,21.6479]]]";
    String[] parsed = st.replaceAll("[^\\d.,]+", "").split(",");    
}

Output:

enter image description here

Upvotes: 0

callOfCode
callOfCode

Reputation: 1026

You can do this with one line:

List<String> list = Arrays.asList(t.replaceAll("\\[", "").replaceAll("\\]", "").split(","));

Full code:

package com.stackoverflow;

import java.util.Arrays;
import java.util.List;

public class Demo 
{
    public static void main(String[] args)
    {
        String t = "[[[1.193493,54.6333],[2.093077,31.6235],[6.175355,21.6479]]]";

        List<String> list = Arrays.asList(t.replaceAll("\\[", "").replaceAll("\\]", "").split(","));
        for(String s : list)
        {
            System.out.println(s);
        }
    }
}

Converts string to list of strings and prints it. If you need to convert strings to doubles, use Double.parseDouble(s) in loop.

Upvotes: 0

Scott Weaver
Scott Weaver

Reputation: 7361

You can do it all at one time with this regex:

(?:\D*(\d*\.\d*))+

Upvotes: 0

Related Questions