CLR Regex for fractions
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.
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.
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}$/
精彩评论