正则表达式C#Assert String是Fraction

时间:2012-07-30 15:46:11

标签: c# .net regex fractions

所有

我需要2个可在.NET中运行的正则表达式来检测用户是否输入了一个分数:

  1. 只有没有任何整个部分的小数值(不想检查1 1 / 4,3 1/2等) 仅限:1 / 2,3 / 4,8 / 3等。分子,分母可以是浮点数或整数。

  2. 所有有效分数,例如1 / 3,2 / 3,1 / 4等

  3. 感谢。

2 个答案:

答案 0 :(得分:1)

试试这个:

/// <summary>
/// A regular expression to match fractional expression such as '1 2/3'.
/// It's up to the user to validate that the expression makes sense. In this context, the fractional portion
/// must be less than 1 (e.g., '2 3/2' does not make sense), and the denominator must be non-zero.
/// </summary>
static Regex FractionalNumberPattern = new Regex(@"
    ^                     # anchor the start of the match at the beginning of the string, then...
    (?<integer>-?\d+)     # match the integer portion of the expression, an optionally signed integer, then...
    \s+                   # match one or more whitespace characters, then...
    (?<numerator>\d+)     # match the numerator, an unsigned decimal integer
                          #   consisting of one or more decimal digits), then...
    /                     # match the solidus (fraction separator, vinculum) that separates numerator from denominator
    (?<denominator>\d+)   # match the denominator, an unsigned decimal integer
                          #   consisting of one or more decimal digits), then...
    $                     # anchor the end of the match at the end of the string
    ", RegexOptions.IgnorePatternWhitespace
    );

/// <summary>
/// A regular expression to match a fraction (rational number) in its usual format.
/// The user is responsible for checking that the fraction makes sense in the context
/// (e.g., 12/0 is perfectly legal, but has an undefined value)
/// </summary>
static Regex RationalNumberPattern = new Regex(@"
    ^                     # anchor the start of the match at the beginning of the string, then...
    (?<numerator>-?\d+)   # match the numerator, an optionally signed decimal integer
                          #   consisting of an optional minus sign, followed by one or more decimal digits), then...
    /                     # match the solidus (fraction separator, vinculum) that separates numerator from denominator
    (?<denominator>-?\d+) # match the denominator, an optionally signed decimal integer
                          #   consisting of an optional minus sign, followed by one or more decimal digits), then...
    $                     # anchor the end of the match at the end of the string
    " , RegexOptions.IgnorePatternWhitespace );

答案 1 :(得分:0)

第一次

对于##/##形式的任何分数,其中分子或分母可以是任意长度,您可以使用:

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

在字面斜杠之前和之后立即抓取尽可能多的数字,只要这些数字中至少有一个或多个。如果有一个小数点,它也必须后跟一个或多个数字,但整个组是可选的,只能出现一次。

第二次

假设它必须是一个分数,那么像1这样的整数就不算数了,只需在前面贴上以下内容

\d*\s*

在分数的其余部分之前抓取一些数字和空格。