替换字符串中的单词,正则表达式

时间:2015-02-25 13:50:22

标签: c# regex string

使用String.Replace更改一行中的单词,例如:

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

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

但我需要some_text or some-text or 1 use 1, read 1 or what 1?

如何解决这个问题? Mayby正则表达式还是其他想法?

更新:例如字符串从这个单词开始"发短信一些文字...." Update2:" text-some"

5 个答案:

答案 0 :(得分:0)

您需要使用单词边界和ignorecase i修饰符。

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

DEMO

(?<=\s)肯定的后瞻断言,断言匹配必须以空格字符开头。 (?i)不区分大小写的修饰符。 \b在单词字符和非单词字符之间匹配的单词边界。

答案 1 :(得分:0)

也许这种String.Split + Enumerable.Select + String.Join方法适合您:

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

您想要的结果:some_text or some-text or 1 use 1 read 1 or what 1

答案 2 :(得分:0)

Avinash正则表达式的变体:

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

我没有使用\b因为-是一个字边界,所以我检查文本开头后面的text或{{1}之一接下来是文本的结尾或.,;:?!之一。

答案 3 :(得分:0)

尝试:

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

答案 4 :(得分:0)

使用字符串splitreplace。还必须使用ToLower()

这里的结果与OP的要求完全相同。但必须使用许多if-else和条件检查。实际上,这是逻辑上我们需要思考的方式,如果我们需要实现结果。

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

输出:

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

enter image description here