Reputation: 177
Supposed I have the following strings:
string str1 = "<tag tsdfg> some other random text";
string str2 = "<tag sdfgsdfgfsdg> some other random text";
string str3 = "<tag 1564> some other random text";
i would like to change those strings to
"<tag> some other random text"
Upvotes: 0
Views: 156
Reputation: 82096
You could use a regular expression to replace all the arbitrary text inside the tag
Regex.Replace("<tag tsdfg> some random text", @"<(.*)?\s+(.*)?>", "<$1>");
This will effectively replace any text, after whitespace, at the end of any tag.
Upvotes: 1
Reputation: 18655
Let's make it at least once unlike the other solutions not about removing or replacing but extracting ;-]
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 );
Upvotes: 0
Reputation: 1739
you can do this:
str1="<tag>" + str1.Remove(0, str1.IndexOf(">") + 1);
it removes from index 0 to >+1 and then add it to "tag"
Upvotes: 0
Reputation: 11228
You can also do it this way:
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"
Upvotes: 0
Reputation: 28272
Use a regular expression:
str1 = Regex.Replace(str1, @"\<tag.*?\>", "<tag>");
Fiddle:
https://dotnetfiddle.net/LdokRn
Upvotes: 3
Reputation: 62488
If after <tag
there will always be a white-space ,then you can use Split()
this way:
string str1 = "<tag tsdfg> some other random text";
string values = str1.Split(' ')[0]+">";
Upvotes: 1
Reputation: 1550
try
str1.Replace((str1.Substring(str1.IndexOf("<"), str1.IndexOf(">"))), "<tag>");
Upvotes: 1