Domanda

I wanna parse a string like {"aaa","bbb", "ccc"} to aaa,bbb,ccc. How can I do it in regex in java? I've tried to write code as below:

String s = "{\"aaa\",\"bbb\", \"ccc\"}";
Pattern pattern = Pattern.compile("\\{\\\"([\\w]*)\\\"([\\s]*,[\\s]*\\\"([\\w]*)\\\")*}");
Matcher matcher = pattern.matcher(s);
if(matcher.find())      {
    StringBuilder sb = new StringBuilder();
    int cnt = matcher.groupCount();
    for(int i = 0; i < cnt; ++i)        {
        System.out.println(matcher.group(i));
    }
}

but the output is

{"aaa","bbb", "ccc"}
aaa
, "ccc"

I have a feeling that this is something about group and no-greedy match, but I don't know how to write it, could anyone help me? Thanks a lot!

P.S. I know how to do it with method like String.replace, I just wanna know could it be done by regex. Thanks

Thanks for all your answers and time, but what I want at first is a delegate solution using regex in java, especially group in regex. I want to know how to use group to solve it.

È stato utile?

Soluzione

RegEx ONLY matching: quite complex

RegEx Pattern: (?:\{(?=(?:"[^"]+"(?:, ?|(?=\})))*\})|(?!^)\G, ?)"([^"]+)"
Note: it needs the global modifier g, needs escaping, works with unlimited number of tokens

Explained demo here: http://regex101.com/r/iE9gS1

Altri suggerimenti

Try this.

import java.util.*;
public class Main{

    public static void main(String[] args){
        String s = "{\"aaa\",\"bbb\", \"ccc\"}";
        s = s.substring(1,s.length() -1 );
        s = s.replace("\"","");
        String[] sa = s.split(", ?");
        for (int i = 0; i < sa.length; i++)
            System.out.println(sa[i]);
    }   
}

Try this sample code :

public class RegexTester {
public static void main(String[] args) throws Exception {
    String data = "{\"aaa\",\"bbb\", \"ccc\"}";

    String modifiedData = data.replaceAll("\\{|\"|\\}", "");

    System.out.println("Modified data : " + modifiedData);
}

Using regex try this pattarn :

Pattern pattern = Pattern.compile("\\{\"(.+?)\"(,?)\"(.+?)\"(,?)\\s*\"(.+?)\"");
    Matcher matcher = pattern.matcher(data);
    System.out.println("Started");
    while (matcher.find()) {

        System.out.print(matcher.group(1));
        System.out.print(matcher.group(2));
        System.out.print(matcher.group(3));
        System.out.print(matcher.group(4));
        System.out.print(matcher.group(5));
    }

Hope this addresses your issue.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top