2013-10-04 84 views
1

我的程序旨在根據特定關鍵字在字符串內搜索圖片url。它實際上工作正常,唯一的問題是「搜索未找到」錯誤。 由於某些原因,它的代碼沒有得到這個「if」,並且如果沒有找到匹配(last if),不會返回任何錯誤。在字符串中查找圖片url

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Net; 
using System.Text.RegularExpressions; 

namespace ConsoleApplication3 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      using (WebClient client = new WebClient()) 
      { 
       int count = 0; 
       Regex SearchItem = new Regex("http://.+?\\.jpg"); 
       string SearchValue = "fgdfgdf"; 
       string htmlCode = "fsdflkjsdfkjsdfkjdsflkhttp://www.dssdtanya.jpgfsdf;ldsmfs;dlfms;dmfs"; 
       Match matches = SearchItem.Match(htmlCode); 

       while (matches.Success) 
       { 
        string test = matches.ToString(); 
        if (test.Contains(SearchValue)) 
        { 
         count++; 
         Console.WriteLine("Result #{0}: '{1}' found in the source code at position {2}.",count, matches.Value, matches.Index); 
         matches = matches.NextMatch(); 
        } 
       } 

       Console.WriteLine(count); 
       if (count == 0) { Console.WriteLine("search not found."); } 
       Console.ReadKey(); 
      } 
     } 
    } 
} 
+0

這可能會幫助您http://stackoverflow.com/questions/6172748/regular-expression-for-image-url – Vivekh

回答

0

如果第一個測試不包含搜索值,程序將進入無限循環。將您的代碼更改爲:

while (matches.Success) 
{ 
    string test = matches.ToString(); 
    if (test.Contains(SearchValue)) 
    { 
     count++; 
     Console.WriteLine("Result #{0}: '{1}' found in the source code at position {2}.", count, matches.Value, matches.Index); 
    } 
    matches = matches.NextMatch(); //moved this outside the if 
}