Reputation: 971
I need to split the string to the substings in order to sort them to quoted and not quoted ones. The single quote character is used as a separator, and two single quotes represents an escape sequence and means that they shall not be used for splitting.
For example:
"111 '222''22' 3333"
shall be splitted as
"111", "222''22", "3333"
no matter with or without whitespaces.
So, I wrote the following code, but it does not work. Tried lookbehind with "\\'(?<!\\')"
as well, but with no success. Please help
String rgxSplit="\\'(?!\\')";
String text="";
Scanner s=new Scanner(System.in);
System.out.println("\""+rgxSplit+"\"");
text=s.nextLine();
while(!text.equals(""))
{
String [] splitted=text.split(rgxSplit);
for(int i=0;i<splitted.length;i++)
{
if(i%2==0)
{
System.out.println("+" + splitted[i]);
}
else
{
System.out.println("-" + splitted[i]);
}
}
text=s.nextLine();
}
Output:
$ java ParseTest
"\'(?!\')"
111 '222''22' 3333
+111
-222'
+22
- 3333
Upvotes: 1
Views: 1190
Reputation: 1146
This should split on a single quote (when it is not doubled), and in the case of three consecutive, it will group the first two and will split on the third.
String [] splitted=text.split("(?<!') *' *(?!')|(?<='') *' *");
Upvotes: 2
Reputation: 424983
To split on single apostrophes use look arounds both sides of the apostrophe:
String[] parts = str.split(" *(?<!')'(?!') *");
See live demo on ideone.
Upvotes: 0