本文介绍了方法有与string.replace只命中"整个单词QUOT;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要一种方法来有这样的:
I need a way to have this:
"test, and test but not testing. But yes to test".Replace("test", "text")
返回这样的:
return this:
"text, and text but not testing. But yes to text"
基本上我想要替换整个单词,而不是部分匹配。
Basically I want to replace whole words, but not partial matches.
注:我将不得不使用VB这个(SSRS 2008 code),而C#是我正常的语言,所以在任何的反应都很好
NOTE: I am going to have to use VB for this (SSRS 2008 code), but C# is my normal language, so responses in either are fine.
推荐答案
一个正则表达式是最简单的方法:
A regex is the easiest approach:
string input = "test, and test but not testing. But yes to test";
string pattern = @"\btest\b";
string replace = "text";
string result = Regex.Replace(input, pattern, replace);
Console.WriteLine(result);
该模式的重要组成部分,是 \ b
元字符,它匹配的单词边界。如果你需要它是区分大小写的使用 RegexOptions.IgnoreCase
:
The important part of the pattern is the \b
metacharacter, which matches on word boundaries. If you need it to be case-insensitive use RegexOptions.IgnoreCase
:
Regex.Replace(input, pattern, replace, RegexOptions.IgnoreCase);
这篇关于方法有与string.replace只命中"整个单词QUOT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!