@Eluvatar の提案を使用して、各部分の間にスペースを想定します。
Calendar cal = Calendar.getInstance();
String original = "2 years 10 weeks 3 days 6 hours 7 min ago";
// Split on whitespace separators ("\s+" means "one or more whitespace characters"),
// having trimmed whitespace at beginning and end.
String[] split = original.trim().split("\s+");
// Now parse each entry
int num = split.length;
int pos = 0;
while ((num-pos) >= 2) {
if (split[pos].regionMatches(true, 0, "year", 0, 4)) {
cal.add(Calendar.YEAR, -Integer.decode(split[++pos]));
}
else if (split[pos].regionMatches(true, 0, "month", 0, 5)) {
cal.add(Calendar.MONTH, -Integer.decode(split[++pos]));
}
else if (split[pos].regionMatches(true, 0, "week", 0, 4)) {
cal.add(Calendar.WEEK_OF_YEAR, -Integer.decode(split[++pos]));
}
// And so on through the other potential values, note that the last
// number in regionMatches is the number of characters to match.
pos++;
}
「\s+」を「\s+」にする必要がある場合があります。区切り文字として空白文字を使用して文字列を分割するにはどうすればよいですか? を参照してください。.