简体   繁体   English

通过C#中的regex提取图像链接

[英]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. IMG标签仅在某些情况下提供,我想提取链接,即在这种情况下http://imgur.com/a/bwBpM Is there an easy way to do this through regex in C#? 有没有一种简单的方法可以通过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 Url +部分或完整标签

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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