例如,我有下面的代码 string txt="我有像 West, and West; and west, and Western 这样的字符串。”
我想用其他词替换“west”或“West”这个词。但我不想用西方取代西方。
- 我可以在 string.replace 中使用正则表达式吗?我用
inputText.Replace("(\\sWest.\\s)",temp);
它不起作用。
不,但您可以使用 Regex 类。
替换整个单词(而不是单词的一部分)的代码:
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", ">");
来源: http: //www.dotnetperls.com/regex-replace
在 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"
如果您希望它不区分大小写,请使用此代码
string pattern = @"\bwest\b";
string modifiedString = Regex.Replace(input, pattern, strReplacement, RegexOptions.IgnoreCase);
我同意罗伯特哈维的解决方案,除了一个小的修改:
s = Regex.Replace(s, @"\bwest\b", "something", RegexOptions.IgnoreCase);
这将用您的新词替换“West”和“west”
当您使用方法 Replace (Regex.Replace) 时,类 Regex 是静态的。
public static class Extension
{
public static string ReplaceValue(string data,string criteria)
{
return s = Regex.Replace(s, @"\bwest\b", "something");
}
}