如何将这个词与正则表达式完全匹配?

时间:2009-12-08 16:32:12

标签: java regex string string-search

我可能会错误地提出这个问题,但我想做的是以下内容:

给定一个大的字符串,可以是多个100行长匹配并准确替换一个单词并确保它不会替换和匹配任何其他字符串的任何部分。

例如:

Strings to Find = Mac Apple Microsoft Matt Damon I.B.M. Hursley  
Replacement Strings = MacO AppleO MicrosoftO MattDamonP I.B.M.O HursleyL  
Input String (with some of the escape characters included for clarity) =  
"A file to test if it finds different\r\n  
bits and bobs like Mac, Apple and Microsoft.\n  
I.B.M. in Hursley does sum cool stuff!Wow look it's "Matt Damon"\r\n  
Testing something whichwillerrorMac"\n  

输出

"A file to test if it finds different  
bits and bobs like MacO, AppleO and MicrosoftO.  
I.B.M.O in HursleyL do sum cool stuff!Wow look it's "Matt DamonP"  
Testing something whichwillerrorMac"  

我尝试使用字边界使用Regex,尽管这会在最后一行选择'whichwhillerrorMacO'

我也尝试使用StringTokenizer类和各种分隔符来尝试替换单词,但我试图替换的一些单词包含这些分隔符。

是否有可以解决此问题的正则表达式?

1 个答案:

答案 0 :(得分:2)

\b(Mac|Apple)\b替换\$1O\不会触及whichwillerrorMac - 但它会匹配whichwill-Mac