0

I'm actually new to java and I'm happy that the regex works that I found^^ But now I need to know, how to get more than 1 string and the best would be if all would be in an array. Actually I do it like this:

Pattern p = Pattern.compile("name~(.*?)@");
Matcher m = p.matcher(response);

while (m.find()) {
     System.out.println("Found: " + m.group());
}

Can anyone help?

4

1 回答 1

1

You just need to put your results into a List:

final List<String> results = new LinkedList<>();
while (m.find()) {
    results.add(m.group());
}

You can then access the results in the List directly - if you need random access use an ArrayList rather than a LinkedList. If you need an array then simply convert it

final String[] resultArr = results.toArray(new String[results.size()]);

If you're matching multiple items in a String you can help the regex engine out a little by matching [^@] and making it possessive rather than using a reluctant .*

Pattern p = Pattern.compile("name~([^@]++)@");
于 2013-03-30T11:42:30.107 回答