文字列を2つの可能なデリメータ「/」または「//」のリストに分割したいと思います。しかし、それ以上に、デリメータも同じリストに入れる必要があります。GuavaのSplitterまたはjava.util.Scannerではこれを行うことができません。
Scanner s = new Scanner(str);
s.useDelimiter("//|/");
while (s.hasNext()) {
System.out.println(s.delimiter());
System.out.println(s.next());
}
s.delimiter()
を返します//|/
。取得したい/
または//
。
これを実行できる他のライブラリを知っていますか?
私はいくつかのコードを書きました、そしてそれは働きます、しかしそれはあまり良い解決策ではありません:
public static ArrayList<String> processString(String s) {
ArrayList<String> stringList = new ArrayList<String>();
String word = "";
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '/' && i < s.length() && s.charAt(i + 1) == '/') {
if (!word.equals(""))
stringList.add(word);
stringList.add("//");
word = "";
i++;
} else if (s.charAt(i) == '/') {
if (!word.equals(""))
stringList.add(word);
stringList.add("/");
word = "";
}else{
word = word + String.valueOf(s.charAt(i));
}
}
stringList.add(word);
return stringList;
}
返品"some/string//with/slash/or//two"
リストにsome, /, string, //, with, /, slash, /, or, //, two
返品"/some/string//with/slash/or//two"
リストに/, some, /, string, //, with, /, slash, /, or, //, two
返品"//some/string//with/slash/or//two"
リストに//, some, /, string, //, with, /, slash, /, or, //, two