[英]Replace specific text in a textbox C#
I'm trying to implement a solution to remove a URL from a textbox and replace it with ""我正在尝试实施一种解决方案,以从文本框中删除 URL 并将其替换为“”
So something like this:所以是这样的:
"Hey check out this site http://www.anywhere.com" “嘿,看看这个网站 http://www.anywhere.com”
Would become:会成为:
"Hey check out this site <URL Quarantined>" “嘿,看看这个网站 <URL Quarantined>”
This is what I've got at the moment but I don't think I'm doing this correctly, any help would be really appreciated: :)这是我目前所拥有的,但我认为我做的不正确,任何帮助将不胜感激::)
private void btnFilter_Click(object sender, RoutedEventArgs e)
{
if (txtContent.Text.Contains("http:"))
{
txtContent.Text.Replace("http", "<URL Quarrantined>");
}
}
Your example is only replacing "http", of course.当然,您的示例只是替换“http”。 If you want to replace the whole URL you will have to resort to regular expressions like this:如果你想替换整个 URL 你将不得不求助于这样的正则表达式:
Regex regex = new Regex(@"http(s)?://([\w-]+.)+[\w-]+(/[\w- ./?%&=])?");
txtContent.Text = regex.Replace(txtContent.Text, "<URL Quarrantined>");
Find the index of "http" and create a new string:找到“http”的索引并创建一个新字符串:
static string Convert(string s)
{
const string t = "<URL Quarantined>";
int index = s.LastIndexOf("http");
if (index != -1)
return string.Concat(s.AsSpan().Slice(0, s.Length - index + 1), t);
return s;
}
Usage:用法:
string s = Convert("Hey check out this site http://www.anywhere.com");
Or:或者:
txtContent.Text = Convert(txtContent.Text);
The .NET Framework Substring
version allocates an additional string: .NET 框架Substring
版本分配了一个额外的字符串:
static string Convert(string s)
{
const string t = "<URL Quarantined>";
int index = s.LastIndexOf("http");
if (index != -1)
return string.Concat(s.Substring(0, s.Length - index + 1), t);
return s;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.