您的样本数据:
12 days ago
1 minutes ago
5.8 hours ago
3.2 years ago
我的正则表达式:
/^([\d]+(?:\.\d)?)\s(years|months|days|hours|minutes)/
(..............) (...............................)
解释:
^([\d]+ # match one or more digits
(?:\.\d)?) # followed by an optional period and digit
\s # followed by a whitespace character
(years|months|days|hours|minutes) # followed by a unit-of-time word
正则表达式下方的两对括号显示合并到正则表达式中的两个捕获组(反向引用)。
尽管您的问题是关于Java的,但这里有一个使用Perl针对您的数据的正则表达式的现场演示。Perl 代码也在这里供参考:
#!/usr/bin/perl -w
use strict;
use warnings;
my @buf;
while (<DATA>) {
@buf = /^([\d]+(?:\.\d)?)\s(years|months|days|hours|minutes)/;
print "[", join("][", @buf), "]\n";
}
__DATA__
12 days ago
1 minutes ago
5.8 hours ago
3.2 years ago
输出:
[12][days]
[1][minutes]
[5.8][hours]
[3.2][years]