I want to parse a string of 12 (often) different floats in a row (with some irrelevant text in front, marking a field), and want them all to end up in a capturing group of their own, so as to collect them from the matcher one at a time. I've noticed I am succeeding by writing the following:
Pattern lastYearIncomePattern = Pattern.compile("(.+\\{\\s)([0-9]{1,2}\\.[0-9]{3}\\s)([0-9]{1,2}\\.[0-9]{3}\\s)([0-9]{1,2}\\.[0-9]{3}\\s)([0-9]{1,2}\\.[0-9]{3}\\s)([0-9]{1,2开发者_如何学Python}\\.[0-9]{3}\\s)([0-9]{1,2}\\.[0-9]{3}\\s)([0-9]{1,2}\\.[0-9]{3}\\s)([0-9]{1,2}\\.[0-9]{3}\\s)([0-9]{1,2}\\.[0-9]{3}\\s)([0-9]{1,2}\\.[0-9]{3}\\s)([0-9]{1,2}\\.[0-9]{3}\\s)([0-9]{1,2}\\.[0-9]{3}\\s)");
which is an exhausting mass of duplicated code. The part ([0-9]{1,2}\\.[0-9]{3}\\s)
will occur 12 times.
Is there any way of doing this better? I've looked on defining that string for itself and then add it into the regex via some loop and a StringBuilder, but it all seems so overdone. Obviously backreferencing didn't work either, since the 12 values are different.
My first approach was to write ([0-9]{1,2}\\.[0-9]{3}\\s){12}
, but this will put all 12 floats in one long string, and that's not what I want, as I'd need another Pattern to pick off the floats one by one then, and then the duplicate-frenzy solution is preferred.
Thanks
How about this:
Pattern lastYearIncomePattern = java.util.regex.Pattern.compile("(.+\\{\\s)(([0-9]{1,2}\\.[0-9]{3}\\s){12})");
Matcher matcher = lastYearIncomePattern.matcher(input);
boolean found =matcher.find();
if(found){
String[] values= matcher.group(2).split("\\s");
}
It works. Would be interested to see if it can be done in one op like you were hoping.
You could write the regexp to match a single float, and then use Matcher.find(int) to iterate through the occurrences.
精彩评论