[英]Using Regex to replace URLs in a string c#
Hi all trying to use a regex to replace some URLs that are inside of a textbox but think I've set this up incorrectly.大家好,尝试使用正则表达式替换文本框内的一些 URL,但认为我设置不正确。
So my message would look like this:所以我的信息看起来像这样:
Hey check out this site http:\www.anywhere.com嘿,看看这个网站 http:\www.anywhere.com
What I'm trying to do would be replace the link with URL Quarantined like the below and then add the replaced URL to a list:我想要做的是将链接替换为 URL 隔离,如下所示,然后将替换的 URL 添加到列表中:
Hey check out this site URL Quarantined嘿,看看这个网站 URL 已隔离
This is my code below:这是我下面的代码:
public void QuarantineURLS()
{
var listURLS = new List<string>();
var urlReplace = new Regex(@"\b(https?://|www\.)\S+(?=\s|[^\P{P}?]|\z)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
txtContentClean.Text = urlReplace.Replace(txtContent.Text, "<URL Quarrantined>");
}
However the output I'm getting looks like this:但是我得到的 output 看起来像这样:
Hey check out this site http:\URL Quarrantined嘿,看看这个网站 http:\URL Quarantined
Would anyone be able to show me how to implement this correctly谁能告诉我如何正确实施
Using the Replace method, you could make use of a callback.使用 Replace 方法,您可以使用回调。
Note that your url in the question has \\
instead of //
请注意,问题中的 url 有
\\
而不是//
As an example, using the pattern from the question:例如,使用问题中的模式:
var listURLS = new List<string>();
var txt = "Hey check out this site http://www.anywhere.com";
var urlReplace = new Regex(@"\b(https?://|www\.)\S+(?=\s|[^\P{P}?]|\z)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
var txtClean = urlReplace.Replace(txt, m => {
listURLS.Add(m.Value);
return "<URL Quarrantined>";
});
Console.WriteLine(txtClean);
listURLS.ForEach(i => Console.Write("{0}\t", i));
Output Output
Hey check out this site <URL Quarrantined>
http://www.anywhere.com
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.