2016-08-05 18 views
0

C# regex pattern to extract urls from given string - not full html urls but bare links as well正規表現マッチングを使用するか、文字列分割メソッドを使用して、文書からURLを抽出する最も速い方法を知りたいと思います。C#、正規表現または文字列分割を使用して文字列を抽出する

したがって、htmlドキュメントを含む文字列があり、URLを抽出したいとします。

正規表現の方法は、次のようになります。

Regex linkParser = new Regex(@"\b(?:https?://|www\.)\S+\b", RegexOptions.Compiled | RegexOptions.IgnoreCase); 
string rawString = "house home go www.monstermmorpg.com nice hospital http://www.monstermmorpg.com this is incorrect url http://www.monstermmorpg.commerged continue"; 
foreach(Match m in linkParser.Matches(rawString)) 
    MessageBox.Show(m.Value); 

と文字列の分割方法:

string rawString = "house home go www.monstermmorpg.com nice hospital http://www.monstermmorpg.com this is incorrect url http://www.monstermmorpg.commerged continue"; 
var links = rawString.Split("\t\n ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).Where(s => s.StartsWith("http://") || s.StartsWith("www.") || s.StartsWith("https://")); 
foreach (string s in links) 
    MessageBox.Show(s); 

1がそれを行うための最もパフォーマンスの方法ですか?

+0

あなたは「私は私の最初の考えは、私ができる –

+0

との両方にそれを試すことができます私は数日間PCにアクセスすることはできません。 –

+0

「ベンチマークプログラムのストップウォッチいくつかの種類である」であったことを認めることを恥ずかしいストップウォッチ –

答えて

0

分割が高速です。ここではあなたがテストすることができますいくつかのコードは次のとおりです。 dotnetfiddle link

using System; 
using System.Diagnostics; 
using System.Linq; 
using System.Text.RegularExpressions; 

public class Program 
{ 

    public void Main() 
    { 
     Stopwatch sw = new Stopwatch(); 

     sw.Start(); 

     for (int i=0; i < 500; i++) 
     { 
      Regex linkParser = new Regex(@"\b(?:https?://|www\.)\S+\b", RegexOptions.Compiled | RegexOptions.IgnoreCase); 
      string rawString = "house home go www.monstermmorpg.com nice hospital http://www.monstermmorpg.com this is incorrect url http://www.monstermmorpg.commerged continue"; 
     } 

     sw.Stop(); 

     var test1Time = sw.ElapsedMilliseconds; 


     sw.Reset(); 
     sw.Start(); 

     for (int i=0; i < 500; i++) 
     { 
      string rawString = "house home go www.monstermmorpg.com nice hospital http://www.monstermmorpg.com this is incorrect url http://www.monstermmorpg.commerged continue"; 
      var links = rawString.Split("\t\n ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).Where(s => s.StartsWith("http://") || s.StartsWith("www.") || s.StartsWith("https://")); 
     } 

     sw.Stop(); 

     var test2Time = sw.ElapsedMilliseconds; 

     Console.WriteLine("Regex Test: " + test1Time.ToString()); 
     Console.WriteLine("Split Test: " + test2Time.ToString()); 
    } 
} 
+0

素晴らしい。回答ありがとうございました –

+0

答えとして確認するのはどうですか? –

関連する問題