How can I split this string so that it keeps quotes and brackets together?

I am trying to split out a string based on spaces, except if the text is wrapped in ( ) brackets or ' ' quotes.

e.g.

SELECT (name, age) FROM marks WHERE name == 'mark smith';

would split into:

[SELECT, (name, age), FROM, marks, WHERE, name, ==, 'mark smith', ;]

My current regex splits it into:

[SELECT, (name, age), FROM, marks, WHERE, name, ==, 'mark, smith', ;] 

i.e. splits the mark smith quotes.

My regex is currently this: "\s+(?![^(]*\))" and I have tried adding a bit for ‘ ‘ quotes, but havent had any success yet!

Any help greatly appreciated, and thanks in advanced!

Kind regards,

Harry

Answer

Try this.

Pattern pat = Pattern.compile("\(.*?\)|'.*?'|\w+|[^('\s\w]+");
String s = "SELECT (name, age), (a, b) FROM marks WHERE name=='mark smith' or b <> 'Y';";
String[] r = pat.matcher(s).results().map(m -> m.group()).toArray(String[]::new);
for (String e : r)
    System.out.println(e);

output:

SELECT
(name, age)
,
(a, b)
FROM
marks
WHERE
name
==
'mark smith'
or
b
<>
'Y'
;

Leave a Reply

Your email address will not be published. Required fields are marked *