2011-12-09 62 views
-4

我試圖做一個正則表達式將返回true,當它遇到這樣的事情:匹配不等於

MyField1 = 10293856 

MyField1 = 72946392 

數字的字符串總是會一串8位數字。但是,我希望以下情況返回false。這是我唯一需要擔心的情​​況,一串八個九。

MyField1 = 99999999 

我該如何構建一個正則表達式來爲我做這件事?

我想表達,以檢查是否

MyField1 = xxxxxxxx 

其中x是所有數字。但唯一不可能的是全部9。

+4

您希望只有在看到字符串「MyField1 = 99999999」時才返回false? – CanSpice

+0

領先的零 - 好或壞? –

+0

'99999999'究竟有什麼問題?這是確切的字符串嗎? 8位重複數字?或任何數量的重複數字?你需要提供你正在尋找的實際模式。 – Brandon

回答

2

你不需要一個正則表達式。

public static bool Validate(string strNum) 
{ 
    bool ret = false; 
    Int32 num = 0; 
    if (Int32.TryParse(strNum, out num)) 
    { 
     if (num != 99999999) 
     { 
      ret = true; 
     } 
    } 
    return ret; 
} 

你也可以有函數返回的解析INT以及一個out參數或返回。

+0

這是一個非常強大的解決方案。但是,它會拒絕0099999999這可能是運營商想要的,但沒有具體要求。 –

+0

我認爲OP正試圖從文本中提取8位數字 –

3

假設MyField1 = 10293856字符串出現在文件中的一行,這裏是一個正則表達式應該做的伎倆

if (Regex.IsMatch(text, 
    @"# Match 'var = 8digitval', where 8digitval is not all nines. 
    ^    # Anchor to start of line. 
    MyField1[ ]=[ ] # Fixed literal var name & equals sign. 
    (?!9{8}$)  # Assert value is not eight nines. 
    [0-9]{8}   # Value is eight digits. 
    $    # Anchor to end of line. 
    ", 
    RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace)) { 
    // Successful match 
} else { 
    // Match attempt failed 
} 

上述正則表達式將匹配其命名爲硬編碼變量的所有行:MyField1。如果你想匹配其他變量名,(周圍等號空格數量可變的),這其中可能會更你在找什麼:

if (Regex.IsMatch(text, 
    @"# Match 'var = 8digitval', where 8digitval is not all nines. 
    ^   # Anchor to start of line. 
    \w+\s*=\s* # Variable var name & equals sign. 
    (?!9{8}$) # Assert value is not eight nines. 
    [0-9]{8} # Value is eight digits. 
    $   # Anchor to end of line. 
    ", 
    RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace)) { 
    // Successful match 
} else { 
    // Match attempt failed 
} 
+0

我不知道你可以這麼做:(?!9 {8} $)#斷言值不是八個九。 –

0

我假設你解析了這一點文本文件的?您的問題對於輸入的確切性質或您正在做的事情有點不清楚。以下內容使用Regex在文本行中查找名稱和值,然後評估約束。

static void Main() 
{ 
    const string Test = @"MyField1 = 10293856 

MyField1 = 72946392 MyField1 = 99999999 MyField1 = 12356642" ;

Regex exp = new Regex(@"^(?<Name>\w+)\s*=\s*(?<Value>\d{8})\s*$", RegexOptions.Multiline); 
    foreach(Match match in exp.Matches(Test)) 
    { 
     string name = match.Groups["Name"].Value; 
     string value = match.Groups["Value"].Value; 

     if (value != "99999999") 
     { 
      Console.WriteLine("{0} = {1}", name, value); 
     } 
    } 
} 

這是真的接近你就有可能獲得與表達,因爲你不能找到8數字串,然後測試值,看它是否是所有的9

您還可以使用LINQ表達式做到這一點:

Regex exp = new Regex(@"^(?<Name>\w+)\s*=\s*(?<Value>\d{8})\s*$", RegexOptions.Multiline); 
    foreach(Match match in exp.Matches(Test).OfType<Match>().Where(m => m.Groups["Value"].Value != "99999999")) 
     ... 
0
^([0-8]\d{8})|(\d[0-8]\d{7})|(\d{2}[0-8]\d{6})|(\d{3}[0-8]\d{5})|(\d{4}[0-8]\d{4})|(\d{5}[0-8]\d{3})|(\d{6}[0-8]\d{2})|(\d{7}[0-8]\d{1})|(\d{8}[0-8])$