-->

Regular expression to get url collection from stri

2019-08-24 01:42发布

问题:

I have a string.An example is given below.

  [playlist]\r\npath1=url1\r\npath2=url2\r\npath=url3\r\npath4=url4\r\ncount=1

How can I extract path properties values from the above string.There may be many properties other than path properties.

Thr result i am expecting is

url1

url2

url3

url4

I think regular expression is best to do this. Any ideas(regular expressions) regarding the Rgular expression needed. How about using string.split method.. Which one is efficient? ..

Thanks in advance

回答1:

Well, this regex works in your particular example:

path\d?=(.+?)\\r\\n

What isn't immediately obvious is if \r\n in your strings are literally the characters \r\n, or a carriage return + new line. The regex above matches those characters literally. If your text is actually this:

[playlist]
path1=url1
path2=url2
path=url3
path4=url4
count=1

Then this regex will work:

path\d?=(.+?)\n

And a quick example of how to use that in C#:

var str = @"[playlist]\r\npath1=url1\r\npath2=url2\r\npath=url3\r\npath4=url4\r\ncount=1";
var matches = Regex.Matches(str, @"path\d?=(.+?)\\r\\n");
foreach (Match match in matches)
{
    var path = match.Groups[1].Value;
    Console.WriteLine(path);
}


标签: c# regex