Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

I just had a similar requirement, but I wanted to match decimal numbers as well. I came up with the following regex

^-?(?<WholeNumber>\d+)(?<Partial>(\.(?<Decimal>\d+))|(/(?<Denomiator>\d+))|(\s(?<Fraction>\d+/\d+)))?$

Or just this if you don't want named groups

^-?\d+((\.\d+)|(/\d+)|(\s\d+/\d+))?$

To remove the decimal number from validating, it would be shortened to

^-?\d+((/\d+)|(\s\d+/\d+))?$

Hope this helps someone!

try this , just for single fraction and not the whole number

/^\d{1}\/?\d{1}$/
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top