0

全部,

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

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

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

谢谢。

4

2 回答 2

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 );
于 2012-07-30T17:42:09.067 回答
0

为了第一

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

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

只要至少有一个或多个数字,就在斜线前后抓住尽可能多的数字。如果有小数点,它后面也必须跟一个或多个数字,但整个组是可选的,并且只能出现一次。

对于第二个

假设它必须是一个分数,所以一个整数单独喜欢1不会计数,只需将以下内容贴在前面

\d*\s*

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

于 2012-07-30T15:56:36.840 回答