김동현 김동현 - 1 month ago 16
Java Question

Java: splitting a semicolon separated string but ignoring escape+semicolon in quotes

I want to split my query, but didn't get the answer which fits my requirement exactly.

I have my string like below :


select 1;select \\2; select 3\\;copy customer from 's3://mybucket/mydata' credentials 'aws_access_key_id=access_key\\;aws_secret_access_key=secret_key\\;master_symmetric_key=master_key'


Desired output :


select 1

select \\2

select 3\\

copy customer from 's3://mybucket/mydata' credentials 'aws_access_key_id=access_key\\;aws_secret_access_key=secret_key\\;master_symmetric_key=master_key'


I found solution about escaper. But it doesn't fit my requirement.


(?<!\\);


Handling delimiter with escape characters in Java String.split() method

How to ignore escape+semicolon in quotes?

Help me.

Answer

I think that's a sollution:

String line = "select 1;select \\2; select 3\\;copy customer from 's3://mybucket/mydata' credentials 'aws_access_key_id=access_key\\;aws_secret_access_key=secret_key\\;master_symmetric_key=master_key'";
line = line.replace("\\","\\\\");//To avoid missing \
String[] tokens = line.split(";(?=([^']*'[^']*')*[^']*$)");//To split on semmicolons, but not those inside quotes
for(String t : tokens) {
    System.out.println("> "+t);
}

You can test it here http://rextester.com/MLTA75734

Comments