[英]how do i replace exact phrases in c# string.replace
I am trying to ensure that a list of phrases start on their own line by finding them and replacing them with \\n + the phrase. 我正在尝试通过查找短语并将其替换为\\ n +短语来确保短语列表以其各自的开头开始。 eg
例如
your name: joe your age: 28
becomes 变成
my name: joe
your age: 28
I have a file with phrases that i pull and loop through and do the replace. 我有一个包含短语的文件,我可以拉出并循环通过这些短语并进行替换。 Except as there are 2 words in some phrases i use \\b to signify where the phrase starts and ends.
除了某些短语中有2个单词外,我使用\\ b表示该短语的开始和结束位置。
This doesn't seem to work, anybody know why? 这似乎不起作用,有人知道为什么吗?
example - String is 'Name: xxxxxx' does not get edited. 示例-字符串为“名称:xxxxxx”不会被编辑。
output = output.Replace('\b' + "Name" + '\b', "match");
Using regular expressions, accounts for any number of words with any number of spaces: 使用正则表达式可以说明任意数量的单词以及任意数量的空格:
using System.Text.RegularExpressions;
Regex re = new Regex("(?<key>\\w+(\\b\\s+\\w+)*)\\s*:\\s*(?<value>\\w+)");
MatchCollection mc = re.Matches("your name: joe your age: 28 ");
foreach (Match m in mc) {
string key = m.Groups("key").Value;
string value = m.Groups("value").Value;
//accumulate into a list, but I'll just write to console
Console.WriteLine(key + " : " + value);
}
Here is some explanation: 这里是一些解释:
The above regular expression uses named groups, to make code more readable. 上面的正则表达式使用命名组,以使代码更具可读性。
got it 得到它了
for (int headerNo=0; headerNo<headersArray.Length; headerNo++)
{
string searchPhrase = @"\b" + PhraseArray[headerNo] + @"\b";
string newPhrase = "match";
output = Regex.Replace(output, searchPhrase, newPhrase); }
按照示例,您可以执行以下操作:
output = output.Replace("your", "\nyour");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.