472,958 Members | 1,761 Online

# Regular explression help - fractions

C#

I am writing a function that allows the user to enter fractions as answers
(i.e. how many asprin tablets for a dosage?).

I have the first half of the Regex figured out but don't know how to do the
second half. In the snippet "1-2 1/2". I can figure out the part before the
dash but not after. The second part is optional for the user. If it is there
it must be complete
Any hints?

"^([0-9]+|[0-9]+\/[1-9]+|[0-9]+ [0-9]+\/[1-9]+)\$"

t0 = "1" - pass
t1 = "1-1" - pass
t2 = "1/2" - pass
t3 = "1 1/2" - pass
t4 = "1 1/2-2" - pass
t5 = "1 1/2-2 1/2" -pass

f1 = "1-" - fail
f2 = "1 1/2-" - fail
f3 = "1/2 1/2" - fail
f4 = "1/2-1/2-" - fail
f5 = "2-1" - fail ??
Jul 21 '05 #1
2 1327
Stedak wrote:
t0 = "1" - pass
t1 = "1-1" - pass
t2 = "1/2" - pass
t3 = "1 1/2" - pass
t4 = "1 1/2-2" - pass
t5 = "1 1/2-2 1/2" -pass

f1 = "1-" - fail
f2 = "1 1/2-" - fail
f3 = "1/2 1/2" - fail
f4 = "1/2-1/2-" - fail

f5 = "2-1" - fail ??

// IgnorePatternWhitespace|Explicitcapture
^
( (\d+ \s* (\d+ \s* \/ \s* \d+ )? ) | # ln 1
(\d* \s* (\d+ \s* \/ \s* \d+)) ) # ln 2
( # ln 3
\s* - \s* # ln 4
( (\d+ \s* ( \d+ \s* \/ \s* \d+ )?) | # ln 5
(\d* \s* ( \d+ \s* \/ \s* \d+ ) )) # ln 6
)?
\$

// 1: a whole number followed by optional fraction OR
// 2: optional whole number followed by mandatory fraction
// 3: begin optional group
// 4: a dash, with optional white space on either side
// 5: a whole number followed by optional fraction OR
// 6: optional whole number followed by mandatory fraction
// 7: end optional group

--

www.midnightbeach.com
Jul 21 '05 #2
> > f5 = "2-1" - fail ??

Oops, I meant to add that I don't think that there's any way for a
regex to act on the 'meaning' of a match - just match / no-match.

--

www.midnightbeach.com
Jul 21 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.