如何替换字符串的一部分
本文关键字:字符串 一部分 替换 何替换 | 更新日期: 2023-09-27 18:36:46
假设我有以下字符串:
string str1 = "<tag tsdfg> some other random text";
string str2 = "<tag sdfgsdfgfsdg> some other random text";
string str3 = "<tag 1564> some other random text";
我想将这些字符串更改为
"<tag> some other random text"
使用正则表达式:
str1 = Regex.Replace(str1, @"'<tag.*?'>", "<tag>");
小提琴:
https://dotnetfiddle.net/LdokRn
试试
str1.Replace((str1.Substring(str1.IndexOf("<"), str1.IndexOf(">"))), "<tag>");
如果<tag
之后总会有一个空格,那么你可以这样使用Split()
:
string str1 = "<tag tsdfg> some other random text";
string values = str1.Split(' ')[0]+">";
您可以使用正则表达式替换标签内的所有任意文本
Regex.Replace("<tag tsdfg> some random text", @"<(.*)?'s+(.*)?>", "<$1>");
这将有效地替换任何标签末尾空格后的任何文本。
试试看
你也可以这样做:
string str = "<tag tsdfg> some other random text";
string newStr = new string(str.TakeWhile(c => !Char.IsWhiteSpace(c))
.Concat(str.SkipWhile(c => c != '>'))
.ToArray());
Console.WriteLine(newStr); // "<tag> some other random text"
你可以这样做:
str1="<tag>" + str1.Remove(0, str1.IndexOf(">") + 1);
它将索引 0 删除到>+1,然后将其添加到"标签"
让我们至少做一次,不像其他解决方案,不是关于删除或替换而是提取;-]
string str1 = "<tag tsdfg> some other random text";
Match match = Regex.Match(str1, @"'<(tag).+?'>(.+)");
string result = String.Format("<{0}>{1}", match.Groups[1].Value, match.Groups[2].Value);
Console.WriteLine(result );