2014-05-07 125 views
1

我有這樣的代碼:「?goodid」問號之前字面正則表達式匹配

 string source = @"looking for goodid\?=11 and badid\?=01 other text"; 
     string searchTag = @"goodid\?=[\d]*"; 

     while (Regex.IsMatch(source, searchTag)) 
     { 
      Console.WriteLine("found match!"); 
     } 

我試圖找到後到來的ID而不是'badid'後面的那個,所以返回應該是11而不是01.

除非我刪除searchtag中的問號'goodid'前面的文本,否則找不到匹配。我怎樣才能將「goodid」包含在問號旁邊?

回答

2

這裏的問題似乎是,在源字符串@"\?"被解釋爲2個字符,而在正則表達式中@"\?"會匹配一首歌曲le問號。發生這種情況是因爲在正則表達式中?是一個特殊字符,需要轉義。如果你想匹配兩個字符@"\?"那麼正則表達式將看起來像這樣@"goodid\\\?=[\d]*";

這就是說,有一個更容易的解決方案與命名組。

Match m = Regex.Match(source, @"goodid\\\?=(<id>?\d*)"); 

if(m.Success) 
{ 
    Console.WriteLine("Match Found: " + m.Groups["id"].Value); 
} 
0

有了這個小正則表達式

(?<=goodid\\\?=)\d+ 

它採用了lookbehind,該位爲goodid\?=

在C#後面檢查,可以像

string resultString = null; 
try { 
    resultString = Regex.Match(yourstring, @"(?<=goodid\\\?=)\d+", RegexOptions.Multiline).Value; 
} catch (ArgumentException ex) { 
    // Syntax error in the regular expression 
} 
+0

@ ser1019042 C#代碼現在增加了:) –

0

我認爲你的源字符串中有一個冗餘'\',這就是問題所在。如果更改爲:

string source = @"looking for goodid?=11 and badid\?=01 other text"; 

(反斜槓問號被刪除之前)
然後找到匹配(無限次,因爲它是在一個while循環!)。

1

改進

Match m = Regex.Match(source, @"goodid\\\?=(?<id>\d*)"); 

if(m.Success) 
{ 
    Console.WriteLine("Match Found: " + m.Groups["id"].Value); 
} 
//changed <id>? to ?<id>