Regular explression help - fractions

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Stedak

    #1

    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 ??
  • Jon Shemitz

    #2
    Re: Regular explression help - fractions

    Stedak wrote:
    [color=blue]
    > 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 ??[/color]


    // IgnorePatternWh itespace|Explic itcapture
    ^
    ( (\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

    --

    Midnight Beach is Jon Shemitz, a freelance programmer and author. Jon offers software consulting and contract services, and recently finished his 2nd book - .NET 2.0 for Delphi Programmers.

    Comment

    • Jon Shemitz

      #3
      Re: Regular explression help - fractions

      > > 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.

      --

      Midnight Beach is Jon Shemitz, a freelance programmer and author. Jon offers software consulting and contract services, and recently finished his 2nd book - .NET 2.0 for Delphi Programmers.

      Comment

      Working...