[英]regular expressions for floating and non-floating point numbers followed by words
i'm tasked with a problem where there is a particular table column that always has the same type of data in it. 我的任务是有一个特定的表列,该列中始终具有相同类型的数据。 For validation purposes i thought it would be easiest to verify that data based on a pattern match.
为了进行验证,我认为基于模式匹配来验证数据是最容易的。
Example set of data: 示例数据集:
*12 days ago
*1 minutes ago
*5.8 hours ago
*3.2 years ago
(ignore the *) Here is the regex i came up with, but i feel its slightly off: (忽略*)这是我想出的正则表达式,但是我觉得它略有偏离:
String f = "^(?:\\d+|\\d*\\.\\d+)\\s+(\\byears|months|days|hours|minutes\\b)\\s+ (\\bago\\b)$";
Pattern p = p.compile(f);
Matcher m;
if (m.find(retreiveRow(5))) { ...... }
Any assistance would be great! 任何帮助将是巨大的! Many thanks!
非常感谢!
as java string : "^\\\\d+(\\\\.\\\\d+)?\\\ (days|minutes|months|hours|years)\\\ ago$"
作为java字符串:
"^\\\\d+(\\\\.\\\\d+)?\\\ (days|minutes|months|hours|years)\\\ ago$"
as plain regex: ^\\d+(\\.\\d+)?\ (days|minuits|hours|years)\ ago$
作为
^\\d+(\\.\\d+)?\ (days|minuits|hours|years)\ ago$
则表达式: ^\\d+(\\.\\d+)?\ (days|minuits|hours|years)\ ago$
i deliberately restricted the whitespace to only space character. 我故意将空格限制为仅空格字符。 doesnt seem tab and all is applicable here.
似乎没有选项卡,所有适用于此处。
Your sample data: 您的样本数据:
12 days ago
1 minutes ago
5.8 hours ago
3.2 years ago
My regular expression: 我的正则表达式:
/^([\d]+(?:\.\d)?)\s(years|months|days|hours|minutes)/
(..............) (...............................)
Explanation: 说明:
^([\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
The two pairs of parentheses below the regex show the two capture groups (backreferences) incorporated into the regex. 正则表达式下面的两对括号显示了合并到正则表达式中的两个捕获组 (反向引用)。
Although your question is with respect to Java , here's a live demo of this regex against your data using Perl . 尽管您的问题是关于Java的 ,但这是使用Perl针对您的数据进行此正则表达式的实时演示 。 Perl code also here for reference:
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
Outputs: 输出:
[12][days]
[1][minutes]
[5.8][hours]
[3.2][years]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.