如何仅从文本中删除网址并在c#中忽略其他网址

问题描述 投票:0回答:3

我想只删除c#中字符串中URL的最后一个实例。

示例字符串:"sample text http://www.url1.com sample text https://www.url2.com sample text http://www.url3.com"

我想只删除"http://url3.com",并将其他URL保留在字符串中。

字符串函数和正则表达式的某些组合是否有助于实现相同的目标?我尝试了正则表达式,但它删除了URL的所有实例。

编辑:这涉及匹配最后一个URL(每次是随机的)和删除i。

@GaurangDave答案运作良好

c# regex
3个回答
0
投票

我使用通用正则表达式模式从文本中找到url。您可以根据需要进行更改。此示例适用于您的方案。它将从字符串中删除最后一个URL。

string txt = "sample text http://www.url1.com sample" +
             "text https://www.url2.com sample text " +
             "http://www.url3.com";

var matches = Regex.Matches(txt, @"((http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?)");

txt = txt.Replace(matches[matches.Count - 1].Value, string.Empty);

0
投票

这是一个非正则表达式解决方案,如果在最后一个URL之后有额外的文本,它也可以使用:

string input = "sample text http://www.url1.com " +
               "sample text https://www.url2.com " +
               "sample text http://www.url3.com " +
               "extra text";
int pos = input.LastIndexOf("http://", StringComparison.InvariantCultureIgnoreCase);
string lastURL = 
    new string(input.Substring(pos).TakeWhile(c => !char.IsWhiteSpace(c)).ToArray());
string output = input.Substring(0, pos) + input.Substring(pos + lastURL.Length);

Console.WriteLine("Last URL: " + lastURL);
Console.WriteLine("Cleaned text: " + output);

输出:

Last URL: http://www.url3.com
Cleaned text: sample text http://www.url1.com sample text https://www.url2.com sample text  extra text

0
投票

你可以使用这个正则表达式匹配最后一个URL,

http\S*$

并用空字符串替换它。

Demo1

如果可选,在最后一个URL之后可以有空格,您可以选择使用此正则表达式匹配它,

http\S*\s*$

Demo2

如果你想支持更多的协议,你可以在正则表达式中指定不同的协议,如下所示,

(?:file|ftp|http)\S*\s*$

Demo3

C#示例代码,

string str = @"sample text http://www.url1.com sample text https://www.url2.com sample text http://www.url3.com";
string replacedStr = Regex.Replace(str, @"(?:file|ftp|http)\S*\s*$", "");
Console.WriteLine("Result: " + replacedStr);

打印,

Result: sample text http://www.url1.com sample text https://www.url2.com sample text
© www.soinside.com 2019 - 2024. All rights reserved.