Convert fraction to decimal

20 views
Skip to first unread message

Psyclone

unread,
Jun 15, 2009, 4:54:35 PM6/15/09
to Regex
Hey, all. Need some help here.

I have a working PHP script to convert a fraction to a decimal using a
regular expression. The PHP works, but the regex is broken somehow.
Here's what I have:

([0-9]+)?[[:space:]]?(([0-9]+)/([0-9]+))?

The PHP extrapolates this into a base variable, numerator, and
denominator.

So it works if I have 1 1/2, or 2/3. But if I have something like
50/200, it assumes that I mean 5 0/200. I get why it's doing that. I
have a ? next to the space. I've tried doing (([0-9]+)?[[:space:]])?
but that breaks the whole thing and gives me 1's and 0's. Am I on the
right track, here?

I am just not a regexpert, so I need a little push in the right
direction.

Thanks for your time!

J. Allen R. Day

unread,
Jun 16, 2009, 8:09:45 AM6/16/09
to re...@googlegroups.com
On Mon, Jun 15, 2009 at 3:54 PM, Psyclone<jaen...@gmail.com> wrote:
> ([0-9]+)?[[:space:]]?(([0-9]+)/([0-9]+))?

Try this:
(?:([0-9]+)[[:space:]])?(([0-9]+)/([0-9]+))?

It only finds a whole number if the space delimiter is present, rather
than filling as many groups as possible.

A

--
Remember, no matter where you go, there you are. -Buckaroo Banzai

Reply all
Reply to author
Forward
0 new messages