在C# 中,我能否使用正则表达式来替换字符串?

46

例如,我有以下代码:

string txt = "I have strings like West, and West; and west, and Western.";

我想要用其他单词替换“west”或“West”,但不想替换“Western”中的“West”。

  1. 我可以在 string.replace 中使用正则表达式吗?我尝试使用 inputText.Replace("(\\sWest.\\s)",temp); 但没有成功。
8个回答

71
不可以,但是你可以使用Regex类。 替换整个单词的代码(而不是单词的一部分):
string s = "Go west Life is peaceful there";
s = Regex.Replace(s, @"\bwest\b", "something");

看起来还不错,但这将忽略西部和西部。而且它是大小写不敏感的吗? - Tasawer Khan
我认为它做的与我已经在使用的相同,即使用“s=s.Replace(" West ","something");” - Tasawer Khan
它的工作方式类似于字符串s = Regex.Replace(s, @"(\bwest\b)", "something");。它适用于west,west和west; 不太明白为什么 :) - Tasawer Khan
1
"\b" 匹配单词边界。此正则表达式区分大小写,但可以添加 RegexOptions.IgnoreCase(第四个参数)使其不区分大小写。 - Hans Kesting
2
使用 System.Text.RegularExpressions; - John Meyer

39

回答这个问题的答案是不可以 - 你不能在string.Replace中使用正则表达式。

如果你想要使用正则表达式,你必须使用Regex类,正如其他人在他们的答案中所述。


9
是的,可以使用String.Replace方法进行正则表达式替换。 - drkthng

9

你是否看过 Regex.Replace?同时,一定要捕获返回值;Replace (通过任何字符串机制)返回一个新的字符串 - 它不会进行原地替换。


4

尝试使用System.Text.RegularExpressions.Regex类。它具有静态的Replace方法。我不太擅长正则表达式,但是类似于以下内容:

string outputText = Regex.Replace(inputText, "(\\sWest.\\s)", temp);

如果您的正则表达式正确,它应该能够工作。


4
在类之前,将正则表达式插入到代码中。
using System.Text.RegularExpressions;

以下是使用正则表达式进行字符串替换的代码。
string input = "Dot > Not Perls";
// Use Regex.Replace to replace the pattern in the input.
string output = Regex.Replace(input, "some string", ">");

source : http://www.dotnetperls.com/regex-replace


3

如果您希望不区分大小写,请使用此代码

string pattern = @"\bwest\b";
string modifiedString = Regex.Replace(input, pattern, strReplacement, RegexOptions.IgnoreCase);

3
在Java中,String#replace接受正则表达式格式的字符串,但是C#也可以使用扩展来实现这一点:
public static string ReplaceX(this string text, string regex, string replacement) {
    return Regex.Replace(text, regex, replacement);
}

并且像这样使用:

var text = "      space          more spaces  ";
text.Trim().ReplaceX(@"\s+", " "); // "space more spaces"

1

我同意Robert Harvey的解决方案,只是需要做一个小修改:

s = Regex.Replace(s, @"\bwest\b", "something", RegexOptions.IgnoreCase);

这将用你的新词替换“West”和“west”


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接