[英]how to get many strings between two strings or two characters
我將此文本標記如下:
∅habbaz∅abdelkrim∅habbaz∅abdelkrim∅habbaz∅abdelkrim
我想獲取字符∅
之間的所有字符串。 我嘗試了以下方法:
ArrayList<String> ta = new ArrayList();
String test=t2.getText();
String str = test;
Pattern pattern = Pattern.compile("∅(.*?)∅");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
ta.add(matcher.group(1));
}
t3.setText(ta.toString());
它應該給我:
[哈巴茲,阿卜杜勒克里姆,哈巴茲,阿卜杜勒克里姆,哈巴茲,阿卜杜勒克里姆]
但這只給了我:
[哈巴茲,哈巴茲,哈巴茲]
如果要使用正則表達式解決方案,請嘗試以下操作:
Pattern pattern = Pattern.compile("∅([^∅]*)");
此模式將匹配∅,然后再加上任意數量的non-∅,這可以解決問題。
使用split
:
String input = "∅habbaz∅abdelkrim∅habbaz∅abdelkrim∅habbaz∅abdelkrim";
String[] tokens = input.split("∅");
這將產生定界符之間的那些字符串的數組。 需要注意的是數組中的第一個字符串將是""
,空字符串,因為你的輸入字符串分隔符開始∅
。 為了避免這種情況,請在分割之前( if (input.startsWith("∅")) {input = input.substring(1);}
)使用輸入的子字符串,或者處理結果標記以排除任何空字符串。
要將標記轉換為ArrayList
,請使用以下命令:
ArrayList ta = new ArrayList<Element>(Arrays.asList(tokens))
或者您可以這樣寫:
List ta = Arrays.asList(input.split("∅"));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.