views:

76

answers:

3

I'd like some help for detecting the following expressions with RegEx

string "(x/x)" where x is any number from 0-999. string "x of x" where x is any number from 0-999.

Typically, the string is a marker for a set, i.e. 4 of 10 things, or (3/5) where the first number is the item and the second number is the total.

Thanks

+1  A: 

How about

"\d{1,3}/\d{1,3}"

and

"\d{1,3} of \d{1,3}"

Sijin
Looks good. Let me give it a go before I mark it. Thanks
Jordan
This will match 000 and the like, which may or may not be acceptable. And in Perl 5.8 and 5.10 \d will match things that are not [0-9] (such as MONGOLIAN DIGIT 5 U+1815)
Chas. Owens
Good point. /d may not be as explicit as I need it to be. Thanks
Jordan
+1  A: 
\([0-9]+\/[0-9]+\)

and

[0-9]+ of [0-9]+
hometoast
This will match 000 and the like, which may or may not be acceptable.
Chas. Owens
+1  A: 

See How to match numbers between X and Y with regexp?.

#!/usr/bin/perl

use strict;
use warnings;

my $num_re = qr/[0-9]|[1-9][0-9]|[1-9][0-9]{2}/;
for my $s qw( 1/10 100/500 a/456) {
    if (my ($x, $y) = $s =~ m{^($num_re)/($num_re)$}) {
     print "x is $x and y is $y\n";
    } else {
     print "$s does not match\n";
    }
}

or just

^([0-9]|[1-9][0-9]|[1-9][0-9]{2})\/([0-9]|[1-9][0-9]|[1-9][0-9]{2})$

if you don't mind violating DRY.

Chas. Owens