C# 如何使用正则表达式进行不区分大小写的字符串替换?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1139439/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 09:10:20  来源:igfitidea点击:

How do you do case-insensitive string replacement using regular expressions?

c#.netregex

提问by Josh Kodroff

I know precisely zilch about regular expressions and figured this was as good an opportunity as any to learn at least the most basic of basics.

我对正则表达式非常了解,并认为这是学习至少最基本的基础知识的好机会。

How do I do this case-insensitive string replacement in C# using a regular expression?

如何使用正则表达式在 C# 中进行这种不区分大小写的字符串替换?

myString.Replace("/kg", "").Replace("/KG", "");

(Note that the '/' is a literal.)

(请注意,“/”是文字。)

采纳答案by Jon Skeet

You can use:

您可以使用:

myString = Regex.Replace(myString, "/kg", "", RegexOptions.IgnoreCase);

If you're going to do this a lot of times, you could do:

如果你要这样做很多次,你可以这样做:

// You can reuse this object
Regex regex = new Regex("/kg", RegexOptions.IgnoreCase);
myString = regex.Replace(myString, "");

Using (?i:/kg)would make just that bitof a larger regular expression case insensitive - personally I prefer to use RegexOptionsto make an option affect the whole pattern.

使用(?i:/kg)将使这一点位较大的正则表达式不区分大小写的-我个人更喜欢使用RegexOptions作出的选择会影响整个格局。

MSDN has pretty reasonable documentationof .NET regular expressions.

MSDN 有相当合理的 .NET 正则表达式文档

回答by Philippe Leybaert

It depends what you want to achieve. I assume you want to remove a sequence of characters after a slash?

这取决于您想要实现的目标。我假设您想在斜杠后删除一系列字符?

string replaced = Regex.Replace(input,"/[a-zA-Z]+","");

or

或者

string replaced = Regex.Replace(input,"/[a-z]+","",RegexOptions.IgnoreCase);

回答by tom.dietrich

"/[kK][gG]" or "(?i:/kg)" will match for you.

"/[kK][gG]" 或 "(?i:/kg)" 将为您匹配。

declare a new regex object, passing in one of those as your contents. Then run regex.replace.

声明一个新的正则表达式对象,将其中一个作为您的内容传递。然后运行regex.replace。

回答by Tim Hoolihan

    Regex regex = new Regex(@"/kg", RegexOptions.IgnoreCase );
    regex.Replace(input, "");

回答by Guffa

Like this:

像这样:

myString = Regex.Replace(myString, "/[Kk][Gg]", String.Empty);

Note that it will also handle the combinations /kG and /Kg, so it does more than your string replacement example.

请注意,它还将处理 /kG 和 /Kg 的组合,因此它比您的字符串替换示例做得更多。

If you only want to handle the specific combinations /kg and /KG:

如果您只想处理特定的组合 /kg 和 /KG:

myString = Regex.Replace(myString, "/(?:kg|KG)", String.Empty);

回答by Brad

Hereis an example using the Regex.replace function.

是使用 Regex.replace 函数的示例。