Reputation: 23
I would like some help with the following question.
I have the following string
1,1,0,3, '2014-12-02 12:15:13', '2015-05-20', 'string', 'other string', 1,2,1, NULL, '', '', NULL, NULL, NULL
and would make the split and put in an array only those quoted ignoring others. You could even separate by commas, but the sequences vary.
I am using the following regex:
String splitStr[] = str.split("\'([^\\']*)\'");
but the output is as follows:
1,1,0,3,, ,,,, ,,, 1,2,1, NULL,, ,,, NULL, NULL, NULL
What I need is exactly the opposite, something like this:
'2014-12-02 12:15:13', '2015-05-20', 'string', 'other string','', ''
Upvotes: 1
Views: 63
Reputation: 41178
Regex doesn't support state, so it's basically impossible to do this as a general case. You can't "count" how many quote marks you've seen in regex.
You can find libraries to do things like this or loop through the String and split it either matching it yourself or using a pattern matcher.
Upvotes: 0
Reputation: 785058
You can do this in Java:
String str = str = "1,1,0,3, '2014-12-02 12:15:13', '2015-05-\\'20', 'string', 'other string', 1,2,1, NULL, '', '', NULL, NULL, NULL";
Pattern p = Pattern.compile("'([^'\\\\]*(?:\\\\.[^'\\\\]*)*)'");
Matcher m = p.matcher(str);
while (m.find()) {
System.out.println("val: [" + m.group(1) + ']');
}
Output:
val: [2014-12-02 12:15:13]
val: [2015-05-\'20]
val: [string]
val: [other string]
val: []
val: []
Upvotes: 3