我想将标签大写之间的文本替换为大写版本。
有没有办法只使用 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.

最佳答案

我愿意,

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 标记替换为空字符串并打印最终输出。
  • 关于c# - 正则表达式更改文本大小写,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27546468/

    10-10 23:39