Regular explression help - fractions

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

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 ??
 
Stedak said:
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
 
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.
 
Back
Top