tags:

views:

66

answers:

1

I need a CLR Regex for fractions or whole numbers and fractions where

1/2 is correct 12 2/3 is correct too

and a minus sign can popup just before any number.

I first came up with -?([0-9]* )?-?[0-9]+\/-?[0-9]+ but that seems to allow 2/7 12 too for example.

+1  A: 

Well, that regex would be in two parts, the (optional) whole number:

(:?-?\d+ )?

and the fractional part:

-?\d+/-?\d+

And we need to match the complete string; so:

^(:?-?\d+ )?-?\d+/-?\d+$

Testing a bit:

PS> $re=[regex]'^(:?-?\d+ )?-?\d+/-?\d+$'
PS> "1/2","12 1/2","-12 2/3","-5/8","5/-8"|%{$_ -match $re} | gu
True

However, this allows for "-12 -2/-3" as well, or things like "1 -1/2" which don't make much sense.

ETA: Your original regex works, too. It just lacked the anchors for begin and end of the string (^ and $, respectively). Adding those make it work correctly.

Joey
tx, and you are right 1 -1/2 doesn't make sense, making it more complicated : -1/2 shoud be possible but 1 -1/2 not..
Peter