使用正则表达式的全字替换

时间:2013-04-16 03:42:46

标签: regex vb.net

我有一个原始单词列表,并替换为我想要将某些句子中原始单词的出现替换为替换单词的单词。

例如我的清单:

theabove      the above
myaddress     my address

所以句子“这是上面的”。将成为“这就是上述。”

我在VB中使用正则表达式,如下所示:

Dim strPattern As String
Dim regex As New RegExp

regex.Global = True

If Not IsEmpty(myReplacementList) Then
  For intRow = 0 To UBound(myReplacementList, 2)
       strReplaceWith = IIf(IsNull(myReplacementList(COL_REPLACEMENTWORD, intRow)), " ", varReplacements(COL_REPLACEMENTWORD, intRow))
       strPattern = "\b" & myReplacementList(COL_ORIGINALWORD, intRow) & "\b"
       regex.Pattern = strPattern

       TextToCleanUp = regex.Replace(TextToReplace, strReplaceWith)
  Next
End If

我将myReplacementList列表中的所有条目与我要处理的文本TextToReplace循环,并且替换必须是整个单词,所以我在原始单词周围使用了“\ b”标记。

它运作良好但是当原始单词包含一些特殊字符时我遇到了问题,例如

overla)   overlay

我试图在模式中逃避),但它不起作用:

\boverla\)\\b

我不能用这个词替换“这个词有重叠”的句子。“ “这个词与那个词重叠。”

不确定缺少什么?正则表达式是否适合上述场景?

1 个答案:

答案 0 :(得分:1)

我会使用string.replace()。 这样你就不必逃避特殊的角色..只有这些:“”! 请参阅此处以获取示例:http://www.dotnetperls.com/replace-vbnet

如果您正在寻找模式,正则表达式很好。或者重命名你的mp3收藏;-)等等。但在你的情况下,我会使用string.replace()。