简体   繁体   中英

Replace word in string, regular expression

Use String.Replace to change word in line, for exapmle:

string s = "some_text or some-text or Text use text, read text or what text?";
            s = s.Replace("text", "1");

Result: some_1 or some-1 or Text use 1, read 1 or what 1?

but i need some_text or some-text or 1 use 1, read 1 or what 1?

How to fix this? Mayby regular expression or somethink else?

Update: for example string beginning on this word "Text some text ...." Update2: "text-some"

You need to use word boundaries along with the ignorecase i modifier.

string replaced = Regex.Replace(yourString, @"(?i)(?<=\s)text\b", "1");

DEMO

(?<=\\s) positive lookbehind assertion which asserts that the match must be preceded by a space character. (?i) case insensitive modifier. \\b word boundary which matches between a word character and a non-word character.

Maybe this String.Split + Enumerable.Select + String.Join approach works for you:

char[] wordDelimiter = new[] { ' ','\t', ',', '.', '!', '?', ';', ':', '/', '\\', '[', ']', '(', ')', '<', '>', '@', '"', '\'' };
var newWords = s.Split(wordDelimiter)
    .Select(w => w.Equals("text", StringComparison.InvariantCultureIgnoreCase) ? "1" : w);
string result = String.Join(" ", newWords);

Your desired result: some_text or some-text or 1 use 1 read 1 or what 1

Variant of Avinash's Regex:

string replaced = Regex.Replace(s, @"(?i)(?<=^|[.,;:?! ])text(?=$|[.,;:?! ])", "1");

I don't use the \\b because the - is a word boundary, so I check for text that follows the beginning of the text or one of .,;:?! and that is followed by end of the text or one of .,;:?! .

尝试:

s= Regex.Replace( Regex.Replace( s, "^text", "1", RegexOptions.IgnoreCase), "\\stext", " 1", RegexOptions.IgnoreCase);

Using string split and replace . Also had to use ToLower()

Here the result is exactly same as the OP's requirement. But had to use many if-else and condition checking. Actually this is the way logically we need to think if we need to achieve the result.

 string s = "some_text or some-text or Text use text, read text or what text?"; 
 string[] arr = s.Split(' '); // < separate by space

 StringBuilder sb = new StringBuilder(); // String builder instance

 foreach (string item in arr)
 {
        // Take to lower and check for text/Text but not _text , -Text 
        if (!item.ToLower().Contains("-text") && !item.ToLower().Contains("_text") && item.ToLower().Contains("text"))
        {
            // Simply replace Text or text 
            sb.Append(item.ToLower().Replace("text","1"));
        }
        else {
            // Else simply append 
            sb.Append(item);
        }
        sb.Append(' ');  // <= Adding space 
   }

    Console.WriteLine(sb.ToString()); // <= Printing the output

    Console.ReadKey();

Output :

some_text or some-text or 1 use 1, read 1 or what 1?

在此输入图像描述

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