2012-08-03 59 views
1

我目前正在使用此代码来替换完全匹配。然而,这不起作用,它也移除了换句话说出现在单词的地方。如何只使用正则表达式替换文本中的确切词c#

例子:

string pattern = "(?i)(flo)"; 
jobTitle = Regex.Replace("Florist of Vinyl Flowers of flo abc", pattern, string.Empty); 

这使得字符串:

乙烯owers的奥里斯

哪项是错误的,应该只从字符串中删除FLO,如果我用途:

string pattern = "(?i)\b(flo)\b"; 

但是这不匹配即使在有一个完整的字,它不会匹配,没有匹配/

UPDATE:

完整的代码运行是这样的:

splitter = wordToremoveTitle.Split('|'); 
if (splitter.Length > 0) 
{ 

    for (int t = 0; t < splitter.Length ; t++) 
    { 
    String pattern = @"(?i)\b(" + splitter[t] + ")\b"; 
    jobTitle = Regex.Replace(jobTitle, pattern, string.Empty); 
    } 
+1

'\ b'是退格的C#字符文字。你需要再次将它转义为'\\ b',或者使用一个逐字串:'string pattern = @“(?i)\ b(flo)\ b”;' – vcsjones 2012-08-03 21:05:23

+0

@vcsjones我做了,改成(?i )\\ b(florist)\ b但是这甚至不会将花店从原始字符串移出来...... string pattern = @“(?i)\ b(”+ splitter [t] +“)\ b”; – confusedMind 2012-08-03 21:08:09

+0

jobTitle = jobTitle.Replace(“flo”,string.Empty); – 2012-08-03 21:11:34

回答

1

你是如此接近,正则表达式:(?i)\bflo\b

string pattern = @"(?i)\bflo\b"; 
jobTitle = Regex.Replace("Florist of Vinyl Flowers", pattern, string.Empty); 

如果词的意思是 “花店” 和 “花”,而不是 “FLO” 使用一个(?i)\b[^ ]*flo[^ ]*\b

+0

我已经申请了确切的说法,仍然没有运气 – confusedMind 2012-08-03 21:10:06

+0

(?i)\\ b [^] * florist [^] * \ b这不会删除,从字符串花店? – confusedMind 2012-08-03 21:21:32

+0

更新的问题请参阅。 – confusedMind 2012-08-03 21:25:26

1

您需要找出“词”对你来说意味着什么,而不是用正则表达式来定义它。

如果它们不匹配“\ b”类别(即@“[\ s,.- $] +”“空格字符,字符串的开头/结尾,标点符号),您可能需要定义边界。 。您可能需要使用@ \ w +” - ‘’。类别如果需要,包括前缀之后,单词的剩余部分

参考 - Character classes

样品taht应该匹配单词开头‘字字符FLO’ :

string pattern = @"(?i)\b(flo\w+)\b"; 
+0

我不想匹配以flo开头的单词,但匹配单词flo并将其替换,但不要将花替换为flo。 – confusedMind 2012-08-03 21:16:56

+0

更新的问题请参阅。 – confusedMind 2012-08-03 21:24:29