I want to replace the text between the tags upcase to its uppercase version. Is there a way to do it by only using Regex.Replace method? (without using IndexOf)
Below is the code I was trying:
string texto = "We are living in a <upcase>yellow submarine</upcase>. We don't have <upcase>anything</upcase> else.";
Console.WriteLine(Regex.Replace(texto, "<upcase>(.*)</upcase>", "$1".ToUpper()));
The expected result is:
We are living in YELLOW SUBMARINE. We don't have ANYTHING else.
but I get:
We are living in yellow submarine. We don't have anything else.
I would do like,
string str = "We are living in a <upcase>yellow submarine</upcase>. We don't have <upcase>anything</upcase> else.";
string result = Regex.Replace(str, "(?<=<upcase>).*?(?=</upcase>)", m => m.ToString().ToUpper());
Console.WriteLine(Regex.Replace(result, "</?upcase>", ""));
Output:
We are living in a YELLOW SUBMARINE. We don't have ANYTHING else.
IDEONE
Explanation:
(?<=<upcase>).*?(?=</upcase>) - Matches the text which was present inbetween <upcase> ,</upcase> tags. (?<=...) called positive lookbehind assertion, here it asserts that the match must be preceded by <upcase> string. (?=</upcase>) called positive lookahead which asserts that the match must be followed by </upcase> string. So the second line of code changes all the matched characters to uppercase and stores the result to the result variable.
/? optional / (forward slash). So the third line of code replaces all the <upcase> or </upcase> tags present in the result variable with an empty string and prints the final output.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With