By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,741 Members | 1,979 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,741 IT Pros & Developers. It's quick & easy.

Regular explression help - fractions

P: n/a
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
Share this Question
Share on Google+
2 Replies


P: n/a
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

P: n/a
> > 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 discussion thread is closed

Replies have been disabled for this discussion.