您可以使用正則表達式\(([^)]*)\)
捕捉一切的括號內。
這是示例代碼
輸出
got string 192.168.0.112 for further processing.
got string 192.168.0.166 for further processing.
got string 192.168.0.112 for further processing.
got string 192.168.0.166 for further processing.
got string 192.168.0.106 for further processing.
代碼
import java.util.regex.*;
import java.util.*;
public class HelloWorld {
public static void main(String[] args) {
List <String> allMatches = new ArrayList <String>();
Matcher m = Pattern.compile("\\(([^)]*)\\)")
.matcher("(192.168.0.112)(192.168.0.166)(192.168.0.112)(192.168.0.166)(192.168.0.106)");
while (m.find())
allMatches.add(m.group(1));
for (String match: allMatches)
myFunction(match);
}
public static void myFunction(String string) {
System.out.println("got string " + string + " for further processing.");
//do your processing here
}
}
EDIT 1 -存儲我ndex也可以使用Map
代替List
輸出
Index: 0 - got string 192.168.0.112 for further processing.
Index: 1 - got string 192.168.0.166 for further processing.
Index: 2 - got string 192.168.0.112 for further processing.
Index: 3 - got string 192.168.0.166 for further processing.
Index: 4 - got string 192.168.0.106 for further processing.
代碼
import java.util.regex.*;
import java.util.*;
public class HelloWorld {
public static void main(String[] args) {
int index=0;
Map<Integer, String> allMatches = new HashMap<Integer, String>();
Matcher m = Pattern.compile("\\(([^)]*)\\)")
.matcher("(192.168.0.112)(192.168.0.166)(192.168.0.112)(192.168.0.166)(192.168.0.106)");
while (m.find())
allMatches.put(index++, m.group(1));
for (Map.Entry<Integer, String> match: allMatches.entrySet())
myFunction(match.getKey(), match.getValue());
}
public static void myFunction(int index, String ip) {
System.out.println("Index: " + index + " - got string " + ip + " for further processing.");
//do your processing here
}
}
您還沒有使用正確的關鍵字。爲什麼不搜索諸如「拆分字符串」 –
的東西你想在一些JSP或Java中使用這個嗎? –