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 bring

Console

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

Regex template help for java for comma separation (,)

thanks

+4
source share
4 answers

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 regular expression matches only a comma if it is followed by an even number of double quotes. This way, the commas inside the double quote are not matched, however, all external commas are used to separate your input.

PS: This will only work for balanced lines. this will not work: "a=1,b=\"1,2" , because the double quote is not balanced.

OUTPUT:

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

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

0
source

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

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

Isn't that what you want?

0
source

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

Source: https://habr.com/ru/post/1494436/


All Articles