RegEx for link extraction

I am looking for RegEx to extract links from a URL. The url will look like this:

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

I need to extract the link http://www.abc.comfrom the above URL.

I tried RegEx:

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

This works, but the problem is that it does not truncate all characters after the first occurrence of &.

It would be great if you could modify RegEx so that I just get the link.

Thanks in advance.

+3
source share
4 answers
redirecturl\\?u=([^\"&]+)

This should be truncated when it reaches &or does not exist at all.&

+2
source

What about using the URI class ?

Example:

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
source

\i.e / [\/]

var matchedString = Regex.Match(s,@"[\/]redirecturl[\?]u[\=](?<link>.*)[\/]").Groups["link"];
0
source
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. [[\w@][\w.:@]+]
//      [\w@][\w.:@]+
//          Any character in this class: [\w@]
//          Any character in this class: [\w.:@], one or more repetitions
//  Literal /, zero or one repetitions
//  Any character in this class: [\w\.?=%&=\-@/$,], any number of repetitions

public Regex MyRegex = new Regex(
      "(?<Protocol>\\w+):\\/\\/(?<Domain>[\\w@][\\w.:@]+)\\/?[\\w\\."+
      "?=%&=\\-@/$,]*",
    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();
0
source

Source: https://habr.com/ru/post/1782246/


All Articles