我必须分开一个字符串,要记住,分裂应该在模式改变的地方。
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=??????? );字符串有三种类型的单词。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( ???????????????? );发布于 2014-06-05 04:25:10
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);
}发布于 2014-06-05 03:51:33
好像有人专门为这个特殊情况写了一个类。
试一试:Is there a way to split strings with String.split() and include the delimiters?
发布于 2014-06-05 03:55:16
我不知道从哪里开始使用regex,但我编写了几个应该处理您的情况的方法。
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);还没测试过,但我很确定它会成功的。希望能帮上忙!
https://stackoverflow.com/questions/24051150
复制相似问题