2011-03-11 49 views
1

一個字符串的哈希我想這個大膽的部分從這個字符串:搜索與正則表達式

some other code src='/pages/captcha?t=c&s=**51afb384edfc&h=513cc6f5349b**' `</td><td><input type=text name=captchaenter id=captchaenter size=3` 

這是我的正則表達式不工作:

Regex("src=\\'/pages/captcha\\?t=c&s=([\\d\\w&=]+)\\'", RegexOptions.IgnoreCase) 

在工具正則表達式測試它正在工作。

這怎麼解決?

enter image description here

+0

有用的工具爲測試/創建正則表達式:http://gskinner.com/RegExr/ – jon3laze 2011-03-11 03:35:21

回答

2

基於字符串的正則表達式是從你的工具來測試正則表達式不同。在你的正則表達式中,你有[\ d \ w \ W] +匹配任何字符並且是積極的(即在+之後沒有?使其變得不積極)。所以它可能會匹配一個非常長的字符串,這可能一直到最後的結束引用。

在你的工具中,只有數字,字母,&和=匹配的[\ d \ w & =],所以很顯然它會在結束報價時停止。

-1

我鄙視正則表達式。我會做類似(但不是安全的)這樣的:

private static string GetStuff(string source) 
    { 
     var start = source.IndexOf("s=") + 2; 
     var end = source.IndexOf('\'', start + 3); 
     return source.Substring(start, end - start); 
    } 
+0

笑了。好。 http://stackoverflow.com/questions/4951240/regex-vs-string-manipulation-functions-what-is-better – 2011-03-11 03:54:25

0

正則表達式不一樣。在代碼中之一具有字符類([\\d\\w\\W]+),其是從所述一個不同的工具([\\d\\w&=]+]

0

作品與此代碼完全正常

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Text.RegularExpressions; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      string s = "src='/pages/captcha?t=c&s=51afb384edfc&h=513cc6f5349b' </td><td><input type=text name=captchaenter id=captchaenter size=3"; 
      Regex rgx = new Regex("src=\\'/pages/captcha\\?t=c&s=([\\d\\w\\W]+)\\'", RegexOptions.IgnoreCase); 

      Match m = rgx.Match(s); 
      Console.Write(m.Groups[1]); 

     } 
    } 
} 

它輸出

51afb384edfc&h=513cc6f5349b