简体   繁体   中英

Extracting image link through regex in C#

I have a bunch of links in this format

http://imgur.com/a/bwBpM
http://imgur.com/a/bwBpM[/IMG]
[IMG]http://imgur.com/a/bwBpM
[IMG]http://imgur.com/a/bwBpM[/IMG]

The IMG tags are only supplied in some cases, and I want to extract the link, ie http://imgur.com/a/bwBpM in this case. Is there an easy way to do this through regex in C#?

If you're saying that you have the text in the question in some kind of list and they are always either in the format of:

  1. Just the Url
  2. the Url + partial or full tags

then the easiest thing to do is to run:

url = url.Replace("[IMG]", "").Replace("[/IMG]");

if there are no tags then there is no change, but if the tags are there they will be stripped out.

You could use this pattern:

^(?:\[IMG\])?([^[]*)(?:\[/IMG\])?$

You can get the output using:

var match = Regex.Match(input, @"^(?:\[IMG\])?([^[]*)(?:\[/IMG\])?$");
if (match.Success)
{
    Console.WriteLine(match.Groups[1].Value); // http://imgur.com/a/bwBpM
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM