埋め込まれたタグがないと仮定すると、次のようなことができます。
private List<String> getText(String text){
List<String> result = new ArrayList<String>();
String[] sections = text.split("<pre>");
int i = 0;
for (String s : sections) {
i = s.indexOf("</pre>");
if (i >= 0)
results.add(s.substring(0, i));
}
return result;
}
次の場合に実行されるコードの例
いう:
text = "test text here <pre> item one </pre> and then another item <pre> item 2 </pre> and then some stuff."
したがって、最初に説明するのは次のとおりです。
String[] sections = text.split("<pre");
これにより、文字列の新しい配列が定義され、「テキスト」の文字列分割関数の呼び出し結果に割り当てられます。
この関数は、文字列をで区切られたセクションに分割するため、次の"<pre>"
ようになります。
sections[0] = "test text here"
sections[1] = "item one </pre> and then another item"
sections[2] = "item 2 </pre> and then some stuff."
ご覧のとおり、今必要なのは何かを削除することだけです。その後"</pre>"
、次のビットが入ります。
for (String s : sections)
配列セクションの各要素に文字列を順番に割り当てる「foreach」ループの開始です。
したがって、上記の3つの文字列のそれぞれについて、次のようにします。
i = s.indexOf("</pre>");
if (i >= 0)
results.add(s.substring(0, i));
したがって、文字列にが含まれている場合は</pre>
、最初からからまでの部分文字列を取得し"</pre>"
て、結果に追加します。セクション[1]とセクション[2]にはそれが含まれているため、結果になります。
これがお役に立てば幸いです。
while(true)の使用を避けるためにJavaJugglersソリューションを実装する方法は次のとおりです。
private List<String> getText(String text){
List<String> result = new ArrayList<String>();
int indexStart = text.indexOf("<pre>");
int indexEnd = text.indexOf("</pre>");
while (indexStart >= 0 && indexEnd > indexStart) {
result.add(text.substring(indexStart + 5, indexEnd));
text = text.substring(indexEnd + 6);
indexStart = text.indexOf("<pre>");
indexEnd = text.indexOf("</pre>");
}
return result;
}