2010-12-27 11 views
3

私はRegExを探してURLからリンクを抽出しています。 URLは以下のようになります:RegEx to link

/redirecturl?u=http://www.abc.com/&tkn=Ue4uhv&ui=fWrQfyg46CADA&scr=SSTYQFjAA&mk=4D6GHGLfbQwETR 

私は上記URLからリンクhttp://www.abc.comを抽出する必要があります。

私は正規表現を試してみました:

redirecturl\\?u=(?<link>[^\"]+)& 

これは動作しますが、問題はそれが&の最初の出現の後のすべての文字を切り捨てないということです。

RegExを修正してリンクを取得できるといいですね。

ありがとうございます。

+1

[これを](使用/マッチングのために\すなわちによって特殊文字をエスケープhttp://stackoverflow.com/q/287144/82449)が役に立ちます。 –

答えて

2
redirecturl\\?u=([^\"&]+) 

それは&に達したときに切り捨てるか、すべての

+0

そして、マッチコレクションで2番目のグループを選んでください。 – Ikaso

0

で何&がされていない場合はどうURI classの使用についてのでしょうか?

例:

string toParse = "/redirecturl?u=http://www.abc.com/&amp;tkn=Ue4uhv&amp;ui=fWrQfyg46CADA&amp;scr=SSTYQFjAA&amp;mk=4D6GHGLfbQwETR"; 

// remove "/redirecturl?u=" 
string urlString = toParse.Substring(15,toParse.Length - 15); 

var url = new Uri(urlString); 
var leftPart = url.GetLeftPart(UriPartial.Scheme | UriPartial.Authority); 
// leftPart = "http://www.abc.com" 
0

[\ /]

var matchedString = Regex.Match(s,@"[\/]redirecturl[\?]u[\=](?<link>.*)[\/]").Groups["link"]; 
0
using System.Text.RegularExpressions; 

// A description of the regular expression: 
// 
// [Protocol]: A named capture group. [\w+] 
//  Alphanumeric, one or more repetitions 
// :\/\/ 
//  : 
//  Literal/
//  Literal/
// [Domain]: A named capture group. [[\[email protected]][\w.:@]+] 
//  [\[email protected]][\w.:@]+ 
//   Any character in this class: [\[email protected]] 
//   Any character in this class: [\w.:@], one or more repetitions 
// Literal /, zero or one repetitions 
// Any character in this class: [\w\.?=%&=\[email protected]/$,], any number of repetitions 

public Regex MyRegex = new Regex(
     "(?<Protocol>\\w+):\\/\\/(?<Domain>[\\[email protected]][\\w.:@]+)\\/?[\\w\\."+ 
     "?=%&=\\[email protected]/$,]*", 
    RegexOptions.IgnoreCase 
    | RegexOptions.CultureInvariant 
    | RegexOptions.IgnorePatternWhitespace 
    | RegexOptions.Compiled 
    ); 


// Replace the matched text in the InputText using the replacement pattern 
string result = MyRegex.Replace(InputText,MyRegexReplace); 

// Split the InputText wherever the regex matches 
string[] results = MyRegex.Split(InputText); 

// Capture the first Match, if any, in the InputText 
Match m = MyRegex.Match(InputText); 

// Capture all Matches in the InputText 
MatchCollection ms = MyRegex.Matches(InputText); 

// Test to see if there is a match in the InputText 
bool IsMatch = MyRegex.IsMatch(InputText); 

// Get the names of all the named and numbered capture groups 
string[] GroupNames = MyRegex.GetGroupNames(); 

// Get the numbers of all the named and numbered capture groups 
int[] GroupNumbers = MyRegex.GetGroupNumbers();