除了选择性字符串之外,如何强制文本为大写 C#

How to force text to be Upper case except selective strings c#

C#:

string mystring = "Hello World. & my name is < bob >. Thank You."
Console.Writeline(mystring.ToUpper())

我试图让所有文本都大写,除了--

&  <  > 

因为这些是我的编码,除非文本是小写,否则编码将不起作用。

您可以用 space 拆分字符串,将所有不以 & 开头的项目转为大写并保持其余部分不变,然后重新连接成一个字符串:

string mystring = "Hello World. & my name is < bob >. Thank You.";
string result = string.Join(" ", mystring.Split(' ').Select(m => m.StartsWith("&") ? m : m.ToUpper()));

另一种方法是使用正则表达式匹配 &, 1+ word chars 然后是 ;,匹配并捕获其他 1+ word char chunks 并且只转为大写第 1 组中的内容:

var result = System.Text.RegularExpressions.Regex.Replace(mystring, 
    @"&\w+;|(\w+)", m => 
           m.Groups[1].Success ? m.Groups[1].Value.ToUpper() :
           m.Value
);