java regex pattern split commna

2019-06-27 17:53发布

String line = "a=1,b=\"1,2\",c=\"[d=1,e=1,11]\"";
String[] tokens = line.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)|,(?=\"[\\([^]]*\\)|[^\"]]*\")");
for (String t : tokens) {
System.out.println("> " + t);
}
System.out.println("-----------------------");

Console

> a=1
> b="1,2"
> c=[d=1
> e="1,1"]
-----------------------

I want to result

Console

> a=1
> b="1,2"
> c=[d=1,e="1,1"]
-----------------------

Help for java regex pattern to split comma(,)

Thanks

标签: java regex
4条回答
Deceive 欺骗
2楼-- · 2019-06-27 17:59

I would program it:

public static void main( String argv[] ) {
        String line = "a=1,b=\"1,2\",c=\"[d=1,e=1,11]\"";

        boolean quote = false;
        String token = "";
        List<String> tokens = new ArrayList<String>();
        for( int i=0; i < line.length(); i++ ) {
            char c = line.charAt( i );

            switch( c ) {
                case ',':
                    if( quote ) {
                        token += c;
                    } else {
                        tokens.add( token );
                        token = "";
                    }
                    break;

                case '"':
                case '\'':
                    quote = !quote;
                    token += c;
                    break;

                default:
                    token += c;
                    break;
            }
        }
        tokens.add( token );

        System.out.println( tokens );
    }

output:

[a=1, b="1,2", c="[d=1,e=1,11]"]
查看更多
淡お忘
3楼-- · 2019-06-27 18:01

You can use this code:

String line = "a=1,b=\"1,2\",c=\"[d=1,e=1,11]\"";
String[] tokens = line.split(",(?=(([^\"]*\"){2})*[^\"]*$)");
for (String t : tokens)
    System.out.println("> " + t);

This regex matches a comma ONLY if it is followed by even number of double quotes. Thus commas inside double quote aren't matched however however all outside commas are used for splitting your input.

PS: This will work for balanced quoted strings only .e.g. this won't work: "a=1,b=\"1,2" as double quote is unbalanced.

OUTPUT:

> a=1
> b="1,2"
> c="[d=1,e=1,11]"
查看更多
爷的心禁止访问
4楼-- · 2019-06-27 18:20

Try this one ,(?=\\w=(\".+\"))

查看更多
何必那么认真
5楼-- · 2019-06-27 18:20

I tried your sample code in netbeans, I got this out put.

> a=1
> b="1,2"
> c="[d=1,e=1,11]"  

Isnt this what you want?

查看更多
登录 后发表回答