Changing text regularly

I want to replace the text between the uppercase of the tags with its uppercase. Is there a way to do this using the Regex.Replace method? (without using IndexOf)

Below is the code I tried:

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()));

      

Expected Result:

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.

      

+3


source to share


1 answer


I would like to,

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>)

    - corresponds to the text that was present between the tags <upcase>

    , </upcase>

    . (?<=...)

    called a positive lookbehind assertion , here it states that the match must be preceded by a string <upcase>

    . (?=</upcase>)

    is called a positive lookahead, which asserts that the match must be followed by a string </upcase>

    . So the second line of code changes all matching characters to uppercase and stores the result in a variable result

    .

  • /?

    optional /

    (forward slash). Thus, the third line of code replaces all tags <upcase>

    or </upcase>

    present in the variable with result

    an empty line and prints the final output.

+7


source







All Articles