例如,我有以下代码:
string txt = "I have strings like West, and West; and west, and Western.";
我想要用其他单词替换“west”或“West”,但不想替换“Western”中的“West”。
- 我可以在
string.replace
中使用正则表达式吗?我尝试使用inputText.Replace("(\\sWest.\\s)",temp);
但没有成功。
string s = "Go west Life is peaceful there";
s = Regex.Replace(s, @"\bwest\b", "something");
回答这个问题的答案是不可以 - 你不能在string.Replace中使用正则表达式。
如果你想要使用正则表达式,你必须使用Regex类,正如其他人在他们的答案中所述。
你是否看过 Regex.Replace
?同时,一定要捕获返回值;Replace
(通过任何字符串机制)返回一个新的字符串 - 它不会进行原地替换。
尝试使用System.Text.RegularExpressions.Regex
类。它具有静态的Replace
方法。我不太擅长正则表达式,但是类似于以下内容:
string outputText = Regex.Replace(inputText, "(\\sWest.\\s)", temp);
如果您的正则表达式正确,它应该能够工作。
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", ">");
如果您希望不区分大小写,请使用此代码
string pattern = @"\bwest\b";
string modifiedString = Regex.Replace(input, pattern, strReplacement, RegexOptions.IgnoreCase);
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"
我同意Robert Harvey的解决方案,只是需要做一个小修改:
s = Regex.Replace(s, @"\bwest\b", "something", RegexOptions.IgnoreCase);
这将用你的新词替换“West”和“west”