Reputation: 192
I want to split the string using space and single quote. But two single quotes should be ignored.
Input:
name eq 'a''b'
Output should be:
name
eq
a''b
I tried to use
[^\\s\"(?<!')'(?!')]+|\"[^\"]*\"|(?<!')'(?!')[^(?<!')'(?!')]*(?<!')'(?!')"
but it does not work.
Upvotes: 1
Views: 2944
Reputation: 2664
This can be done without regex
too.
String s = "name eq 'a''b'";
String[] split = new String[3];
Scanner in = new Scanner(s);
split[0] = in.next();
split[1] = in.next();
String temp = in.next();
split[2] = temp.substring(1,temp.length() - 1);
//test output
for(String x : split)
System.out.println(x);
This will print:
name
eq
a''b
If you need a more generic solution you need to provide more details.
Hope this helps.
Upvotes: 0
Reputation: 1026
Hi the actual regex is
"\\s|(?<!')'(?!')"
It produces output array as follows
[name, eq, , a''b]
Upvotes: 1
Reputation: 46841
You can try with Lookaround
Pattern
(?<!')'(?!')
Sample code:
System.out.println(Arrays.toString("name eq 'a''b'".split("(?<!')'(?!')")));
output:
[name eq , a''b]
Pattern explanation:
(?<! look behind to see if there is not:
' '\''
) end of look-behind
' '\''
(?! look ahead to see if there is not:
' '\''
) end of look-ahead
To split based on space or single quote use
*(?<!')[ '](?!') *
sample code:
System.out.println(Arrays.toString("name eq 'a''b'".split(" *(?<!')[ '](?!') *")));
output:
[name, eq, a''b]
Upvotes: 0
Reputation: 48817
The following one should suit your needs:
'(?:[^']|'')+'|[^ ]+
Java example:
String input = "foobar foo bar 'foobar' 'foo bar' 'foo''bar'";
Pattern pattern = Pattern.compile("'(?:[^']|'')+'|[^ ]+");
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
String match = matcher.group();
System.out.println(match);
}
Upvotes: 3
Reputation: 2301
Here is how I would do:
String value = "name eq 'a''b'";
value = value.replaceAll(" '", " ").replaceAll("'$", "");
System.out.println(value);
String[] arr = value.split(" ");
Upvotes: 0