简体   繁体   中英

java regex pattern split commna

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

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 .eg 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]"

试试这个,(?=\\\\w=(\\".+\\"))

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?

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]"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM