正则表达式改变文本案例

vmp*_*vmp 3 c# regex

我想将标签之间的文本替换为大写版本.有没有办法只使用Regex.Replace方法?(不使用IndexOf)

以下是我尝试的代码:

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()));
Run Code Online (Sandbox Code Playgroud)

预期的结果是:

We are living in YELLOW SUBMARINE. We don't have ANYTHING else.
Run Code Online (Sandbox Code Playgroud)

但我得到:

We are living in yellow submarine. We don't have anything else.
Run Code Online (Sandbox Code Playgroud)

Avi*_*Raj 7

我愿意,

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>", ""));
Run Code Online (Sandbox Code Playgroud)

输出:

We are living in a YELLOW SUBMARINE. We don't have ANYTHING else.
Run Code Online (Sandbox Code Playgroud)

IDEONE

说明:

  • (?<=<upcase>).*?(?=</upcase>)- 匹配中间存在的文本<upcase>,</upcase>标签.(?<=...)称为正向lookbehind断言,这里断言匹配必须以<upcase>字符串开头.(?=</upcase>)称为正向前瞻,断言匹配必须后跟</upcase>字符串.因此,第二行代码将所有匹配的字符更改为大写,并将结果存储到result变量中.

  • /?可选/(正斜杠).因此,第三行代码用空字符串替换变量中存在的所有<upcase></upcase>标记,result并打印最终输出.