Use string.Replace to match whole words

后端 未结 3 825
逝去的感伤
逝去的感伤 2021-01-21 16:50

I\'m using NET 2.0 and WinForms.

Currently, I need a code to replace a string with another one in a given text, but in the text it should only look for whole words. What

3条回答
  •  旧巷少年郎
    2021-01-21 17:28

    I think you cannot achieve that string replace any faster (I'm talking about developing time) than by RegExp

            string input = @"COUNTER = $40 CLOCK_COUNTER = $60";
            string pattern = @"\bCOUNTER\b";
            string replacement = "COUNT";
            var regex = new Regex(pattern,RegexOptions.Compiled);
            string result = regex.Replace(input, replacement);
    

    Adding RegexOptions.Compiled makes it faster if you intend to reuse

    -------------------UPDATE-----------------------------

    i remembered about this article that may fit your needs:

    http://www.codeproject.com/KB/string/fastestcscaseinsstringrep.aspx

提交回复
热议问题