简体   繁体   中英

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. 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.

This doesn't seem to work, anybody know why?

example - String is 'Name: xxxxxx' does not get edited.

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:

  • Suppose what you want to the left of the colon (:) is called a key , and what is to the right - a value .
  • These key/value pairs are separated by at least once space. Because of this, value has be exactly one word (otherwise we'd have ambiguity).

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM