How can I replace text using c# regex that starts with "<" and ends with ">", but keep start and end characters and suround found match with {} brackets? All occurrences in text should be replaced.
For example:
This is <my> long <text>
should become
This is {<my>} long {<text>}
.
Thomas is correct -- in this case, you do not need a regular expression. However, if you insist on using one (or want to expand this logic in the future to handle a range of characters), here it is:
var inputString = "This is <my> long <text>";
var newInputString = Regex.Replace(inputString, "(<[^>]+>)", "{$1}");
This regex assumes you are capturing at least one character between the angled brackets.
Why don't you use just replace
;
string text = "This is <my> long <text>";
var replacedText = text.Replace("<", "{<").Replace(">", ">}");
If you have encoded text, you can decode it first;
string text = "This is <my> long <text>";
var replacedText = WebUtility.HtmlDecode(text).Replace("<", "{<").Replace(">", ">}");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.