简体   繁体   English

用C#和正则表达式替换模式之间的char

[英]replace char between pattern with c# and regex

I'm trying to improve a code using RegEx. 我正在尝试使用RegEx改进代码。 Basically I have some patterns and I need to replace with the same pattern but using uppercase. 基本上,我有一些模式,我需要用大写形式替换为相同的模式。

For example: 例如:

".a." “。一种。”

to

".A." “。一种。”

another pattern 另一种模式

"'a" “'一种”

to

"'A" “'一种”

I know a little bit about regex, but I don't know to replace to the same content but on uppercase. 我对regex有所了解,但我不知道要替换为大写形式的相同内容。

As Cyral said: 正如Cyral所说:

var str = "hello.a.world";
str = Regex.Replace(str, @'\.[a-z]\.', x => x.Value.ToUpper());
//str == "hello.A.world"

This tutorial is a great reference for .NET's regular expression engine and regular expressions in general. 本教程是.NET正则表达式引擎和一般正则表达式的很好的参考。

Expresso is a fantastic tool that I use frequently when I work with regular expressions. Expresso是一个很棒的工具,在使用正则表达式时我经常使用它。 It will spell out what the regular expression does, and allows you to test it out on sample text. 它将阐明正则表达式的功能,并允许您在示例文本上对其进行测试。 It also uses the same regex engine as .NET, so if your expression works in Expresso, it will work in C#. 它还使用与.NET相同的正则表达式引擎,因此,如果您的表达式在Expresso中可用,它将在C#中起作用。

Edit: Just to be clear, Cyral's answer is correct, I just wanted to be sure to add these links on to the page, as they are very helpful. 编辑:明确地说,Cyral的答案是正确的,我只是想确保将这些链接添加到页面上,因为它们非常有帮助。

You don't need to use regex, you can just use String.ToUpper 您不需要使用正则表达式,只需使用String.ToUpper

string str = ".a.";
str = str.ToUpper();

EDIT: To replace only from a pattern, run a function on the match: (Where [az] is your own regex) 编辑:要仅从模式中替换,请在匹配项上运行一个函数:(其中[az]是您自己的正则表达式)

str = Regex.Replace(str, @"[a-z]", s => s.Value.ToUpper());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM