Rather than splitting away what you don't want, search for what you do want.
In Java 9+, this can be done easily with streams:
String s = "1qwerty2qwerty3";
System.out.println(Pattern.compile("\\d+")
.matcher(s)
.results()
.limit(2)
.map(MatchResult::group)
.collect(Collectors.toList()));
// or condensed:
System.out.println(Pattern.compile("\\d+").matcher(s).results()
.limit(2).map(r->r.group()).collect(Collectors.toList()));
Disclaimer: Idea of using limit()
taken from answer by Elliott Frisch.
In Java 5+, you need a find()
loop:
List<String> result = new ArrayList<String>();
for (Matcher m = Pattern.compile("\\d+").matcher(s); m.find(); ) {
result.add(m.group());
if (result.size() == 2)
break;
}
System.out.println(result);
Output from both
[1, 2]
The advantage of these, over solution using split()
, is that you won't get an empty string first, if input doesn't start with a digit.
Example
String s = "qwerty1qwerty2qwerty3qwerty";
// Using this answer
System.out.println(Pattern.compile("\\d+")
.matcher(s)
.results()
.limit(2)
.map(MatchResult::group)
.collect(Collectors.toList()));
// Using answer by Elliott Frisch
System.out.println(Stream.of(s.split("\\D+")).limit(2)
.collect(Collectors.toList()));
// Alternate, applying comment to answer by Elliott Frisch
System.out.println(Pattern.compile("\\D+")
.splitAsStream(s)
.limit(2)
.collect(Collectors.toList()));
Output
[1, 2]
[, 1]
[, 1]