简体   繁体   中英

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$"

as plain regex: ^\\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 . Perl code also here for reference:

#!/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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM