Reputation: 1243
This is my number "1508261". In the end I want to have a List of ("15","08","261"). Meaning, the pattern should always create two new numbers with two digits in each and the remaining digits should be all included in the last (third) number.
I tried using this approach but it returns ("1508261"):
Pattern pattern = Pattern.compile("([0-9]{2})([0-9]{2})([0-9]{1,})");
Matcher matcher = pattern.matcher("1508261");
ArrayList<String> list = new ArrayList<String>();
while (matcher.find()) {
list.add(matcher.group());
}
Upvotes: 0
Views: 170
Reputation: 1975
Your snippet tests the whole pattern against the input string, not each group separately. You might want to use Matcher.matches()
and Matcher.group(int)
instead of Matcher.find()
:
Pattern pattern = Pattern.compile("([0-9]{2})([0-9]{2})([0-9]{1,})");
Matcher matcher = pattern.matcher("1508261");
ArrayList<String> list = new ArrayList<String>();
if(matcher.matches()) {
for(int i = 1;i <= matcher.groupCount();i++)
list.add(matcher.group(i));
}
System.out.println(list);
Live example in Ideone here.
Also note that Matcher.group()
and Matcher.group(0)
do the same job. More info can be found in the Oracle Java Regex Tutorial.
Upvotes: 4