Madhura Adawadkar
Madhura Adawadkar

Reputation: 192

Java - Split string based on space and single quote but ignore two single quotes

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

Answers (5)

gkrls
gkrls

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

Mohan Raj B
Mohan Raj B

Reputation: 1026

Hi the actual regex is

"\\s|(?<!')'(?!')"

It produces output array as follows

[name, eq, , a''b]

Upvotes: 1

Braj
Braj

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

sp00m
sp00m

Reputation: 48817

The following one should suit your needs:

'(?:[^']|'')+'|[^ ]+

Regular expression visualization

Debuggex Demo


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);
}

Ideone Demo

Upvotes: 3

user1401472
user1401472

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

Related Questions