Reputation: 153
I have to splitt a string , keeping in mind that split should at the pattern change spot.
String nxy= "xI yam yw 1a 2pro xgr xon xsig yk yn ya 2h 3h xpr xoc yes ysin yn"
String[] patterns=nxy.split( regex=??????? );
String has three types of words. 1. starting with number : 1a, 2h etc. 2. starting with x: xl, xgr, xon etc. 3. starting with y: yam, yn, ye etc.
I need to split it in three types of parts:
1. contains words starting with number
2. contains words starting with x
3. contains words starting with y
in other words string 'nxy' is to be divided into following parts:
xI
yam yw
1a 2pro
xgr xon xsig
yk yn ya
2h 3h
xpr xoc
yes ysin yn
I need help for:
String[] patterns=nxy.split( ???????????????? );
Upvotes: 3
Views: 232
Reputation: 63698
String temp = nxy.replaceAll("(?:\\b(x|y)[^\\s]*(?:(?:\\s+\\1[^\\s]*)*))|(?:(?:\\s+\\d[^\\s]*)+)","$0\n");
for (String o : temp.split("\\n")) {
System.out.println(o);
}
Upvotes: 1
Reputation: 3326
I have no idea where to begin to do that with regex, but I wrote a couple methods that should handle your case.
public List<String> splitByCrazyPattern(String nxy) {
String[] split = nxy.split(" ");
List<String> patterns = new ArrayList();
for(int i = 0; i < split.length(); i++) {
String string = split[i];
while(checkNext(string.substring(0, 1)), string[i+1]) {
i++;
string += " " + split[i];
}
patterns.add(string);
}
return patterns;
}
public boolean checkFirst(String first, String string) {
if (first.equals(string.substring(0,1))) {
return true;
}
if (first.matches("[0-9]") && string.substring(0, 1).matches("[0-9") {
return true;
}
return false;
}
String nxy= "xI yam yw 1a 2pro xgr xon xsig yk yn ya 2h 3h xpr xoc yes ysin yn";
String[] patterns= splitByCrazyPattern(nxy);
Haven't tested, but I'm pretty sure it should work. Hope it helps!
Upvotes: 0
Reputation: 432
Looks like someone wrote a class just for this special case.
Give it a try: Is there a way to split strings with String.split() and include the delimiters?
Upvotes: 0