2012-07-30 80 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);