2012-07-30 77 views
-1

所有,正则表达式C#断言字符串是分数

我需要2个正则表达式,它可以在.NET来检测用户是否在一小部分类型:

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

  2. ALL有效馏分,例如1/3,2/3,1 1/4等

感谢。

+0

#1。 \ d/{1} \ d(我不知道怎么做#2) – ActiveX 2012-07-30 15:57:24

+0

请记住,只有'\ d'只匹配一个数字。要匹配0或更多,可以使用'\ d *'。要再匹配1个,请使用'\ d +'。在同样的逻辑中,在'/'之后不需要'{1}',因为它意味着你的意思是“一个字面斜杠” – 2012-07-30 16:05:05

回答

0

对于第一

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

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

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

对于第二

假设它必须是一小部分,因此整体人数就喜欢1起不到作用,只要坚持正面

\d*\s* 

抓住以下一些数字并在其余部分之前留出空白。

+0

问题要求“2正则表达式”; “允许1 1/4”的例子是第二个正则表达式的要求;第一个例子是“不允许的”1 1/4“例子。 – phoog 2012-07-30 15:57:56

+0

对于#1(第一正则表达式),没有整个部分,对于#2(第二正则表达式)我需要包含整个部分的正则表达式,即。我正在寻找2个不同的正则表达式。 – ActiveX 2012-07-30 15:59:12

+0

Gotcha,给我一分钟编辑然后 – 2012-07-30 15:59:35

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);