2

我对 Regex 的了解并不多,所以这似乎是一个愚蠢的问题。

我将 a 拆分stringstring[]with .Split(' ')
目的是检查单词,或替换任何单词。

我现在遇到的问题是,对于要替换的单词,它必须是完全匹配的,但是按照我拆分它的方式,拆分后的单词可能有(or [

到目前为止,为了解决这个问题,我正在使用这样的东西:
formattedText.Replace(">", "> ").Replace("<", " <").Split(' ').

现在这很好用,但我想合并更多特殊字符,例如[;\\/:*?\"<>|&'].

有没有比我的替换方法更快的方法,比如正则表达式?我觉得我的路线远非最佳答案。

EDIT
This is an (example) string
将被替换为
This is an ( example ) string

4

2 回答 2

4

如果你想替换整个单词,你可以用这样的正则表达式来做到这一点。

string text = "This is an example (example) noexample";
string newText = Regex.Replace(text, @"\bexample\b", "!foo!");

newText将包含"This an !foo! (!foo!) noexample"

这里的关键是\b单词中断元字符。所以它将匹配一行的开头或结尾,以及单词字符 (\w) 和非单词字符 (\W) 之间的转换。它与使用 \w 或 \W 之间的最大区别在于它们不会在行的开头或结尾匹配。

于 2013-06-20T22:07:23.393 回答
0

我觉得这是你想要的正确的东西

如果你想要这些 -> ;\/:*?"<>|&' 符号来替换

string input = "(exam;\\/:*?\"<>|&'ple)";
        Regex reg = new Regex("[;\\/:*?\"<>|&']");
        string result = reg.Replace(input, delegate(Match m)
        {
            return " " + m.Value + " ";
        });

如果要替换除 a-zA-Z0-9_ 之外的所有字符

 string input = "(example)";
        Regex reg = new Regex(@"\W");
        string result = reg.Replace(input, delegate(Match m)
        {
            return " " + m.Value + " ";
        });
于 2013-03-05T10:06:01.733 回答