Search code examples
c#.netregexfractions

Regular Expression C# Assert String is Fraction


All,

I need 2 regex expression that will work in .NET to detect whether the user typed in a fraction:

  1. Only fractional values without any whole parts (don't want to check for 1 1/4, 3 1/2, etc.) ONLY: 1/2, 3/4, 8/3, etc. The numerator, denominator can be floating point or integers.

  2. ALL valid fractions such as 1/3, 2/3, 1 1/4, etc.

Thanks.


Solution

  • For the first

    For any fraction in the form of ##/##, where the numerator or denominator could be of any length, you could just use:

    \d+(\.\d+)?/\d+(\.\d+)?
    

    Grab as many digits as you can immediately before and after a literal slash, as long as there's at least one or more of those digits. If there's a decimal point, it also must be followed by one or more digits, but that whole group is optional and can only appear once.

    For the second

    Assuming it must be a fraction, so a whole number alone like 1 would not count, just stick the following on the front

    \d*\s*
    

    Grab some digits and whitespace before the rest of the fraction.