在regex.replace中忽略区分大小写?

时间:2021-07-02 05:39:30

I have this code to search in a string and replace some text with other text:

我有这个代码在字符串中搜索并用其他文本替换一些文本:

Regex regexText = new Regex(textToReplace);
retval = regexText.Replace(retval, Newtext);

textToReplace may be "welcome" or "client" or anything.

textToReplace可以是“welcome”或“client”或任何东西。

I want to ignore case for textToReplace so that "welcome" and "Welcome" both match.

我想忽略textToReplace的情况,以便“欢迎”和“欢迎”都匹配。

How can I do this?

我怎样才能做到这一点?

3 个解决方案

#1


16  

You may try:

你可以尝试:

Regex regexText = new Regex(textToReplace, RegexOptions.IgnoreCase);

#2


13  

You simply pass the option RegexOptions.IgnoreCase like so:

您只需传递RegexOptions.IgnoreCase选项,如下所示:

Regex regexText = new Regex(textToReplace, RegexOptions.IgnoreCase);
retval = regexText.Replace(retval, Newtext);

Or, if you prefer, you can pass the option directly to the Replace method:

或者,如果您愿意,可以将选项直接传递给Replace方法:

retval = Regex.Replace(retval, textToReplace, Newtext, RegexOptions.IgnoreCase);

A list of the available options you can set for regexes is available at the RegexOptions documentation page.

RegexOptions文档页面提供了可以为regex设置的可用选项列表。

#3


1  

There's a Regex.Replace overload with RegexOptions. Those options include an IgnoreCase value.

有RegexOptions的Regex.Replace重载。这些选项包括IgnoreCase值。

#1


16  

You may try:

你可以尝试:

Regex regexText = new Regex(textToReplace, RegexOptions.IgnoreCase);

#2


13  

You simply pass the option RegexOptions.IgnoreCase like so:

您只需传递RegexOptions.IgnoreCase选项,如下所示:

Regex regexText = new Regex(textToReplace, RegexOptions.IgnoreCase);
retval = regexText.Replace(retval, Newtext);

Or, if you prefer, you can pass the option directly to the Replace method:

或者,如果您愿意,可以将选项直接传递给Replace方法:

retval = Regex.Replace(retval, textToReplace, Newtext, RegexOptions.IgnoreCase);

A list of the available options you can set for regexes is available at the RegexOptions documentation page.

RegexOptions文档页面提供了可以为regex设置的可用选项列表。

#3


1  

There's a Regex.Replace overload with RegexOptions. Those options include an IgnoreCase value.

有RegexOptions的Regex.Replace重载。这些选项包括IgnoreCase值。