我必须拆分一个字符串,记住拆分应该在模式更改点。
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有三种类型的单词。 1.从数字开始:1a,2h等 2.从x:xl,xgr,xon等开始 3.从y:yam,yn,ye等开始。
我需要将它分成三类:
1. contains words starting with number
2. contains words starting with x
3. contains words starting with y
换句话说,字符串' nxy'将分为以下几部分:
xI
yam yw
1a 2pro
xgr xon xsig
yk yn ya
2h 3h
xpr xoc
yes ysin yn
我需要帮助:
String[] patterns=nxy.split( ???????????????? );
答案 0 :(得分:1)
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);
}
答案 1 :(得分:0)
看起来有人为这个特例写了一堂课。
试一试:Is there a way to split strings with String.split() and include the delimiters?
答案 2 :(得分:0)
我不知道从哪里开始使用正则表达式,但我写了几个方法来处理你的情况。
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没有经过测试,但我确信它应该可行。希望它有所帮助!