正则表达式改变文本案例

时间:2014-12-18 12:19:02

标签: 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()));

预期结果是:

We are living in YELLOW SUBMARINE. We don't have ANYTHING else.

但我明白了:

We are living in yellow submarine. We don't have anything else.

1 个答案:

答案 0 :(得分: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>", ""));

输出:

We are living in a YELLOW SUBMARINE. We don't have ANYTHING else.

IDEONE

<强>解释

  • (?<=<upcase>).*?(?=</upcase>) - 匹配<upcase></upcase>标记之间的文字。 (?<=...)名为positive lookbehind assertion,此处声明匹配必须以<upcase>字符串开头。 (?=</upcase>)称为正向前瞻,它声称匹配必须后跟</upcase>字符串。因此,第二行代码将所有匹配的字符更改为大写,并将结果存储到result变量。

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