c# – 正则表达式改变文本案例
发布时间:2020-12-16 02:04:03 所属栏目:百科 来源:网络整理
导读:我想将标签之间的文本替换为大写版本. 有没有办法只使用 Regex.Replace方法? (不使用IndexOf) 以下是我尝试的代码: string texto = "We are living in a upcaseyellow submarine/upcase. We don't have upcaseanything/upcase else."; Console.WriteLine(R
我想将标签之间的文本替换为大写版本.
有没有办法只使用 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>串.因此,第二行代码将所有匹配的字符更改为大写,并将结果存储到结果变量中.> /?可选/(正斜杠).所以第三行代码替换了所有< upcase>或< / upcase>标签以空字符串形式存在于结果变量中并打印最终输出. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |