【问题标题】:Whole word replacements using Regular Expression使用正则表达式替换整个单词
【发布时间】:2013-04-16 13:27:21
【问题描述】:

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

例如我的清单:

theabove      the above
myaddress     my address

所以句子“This is theabove”。将变为“这是上面的。”

我在 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

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

不确定缺少什么?正则表达式是上述场景的方法吗?

【问题讨论】:

    标签: regex vb.net


    【解决方案1】:

    我会使用 string.replace()。 这样你就不必逃避特殊字符..只有这些:“”! 有关示例,请参见此处:http://www.dotnetperls.com/replace-vbnet

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

    【讨论】:

    • 谢谢@gilu,我对 string.replace 的问题是,它不能轻松处理整个单词的替换。例如,如果我将“carr”替换为“car”,我的句子“This is my carr and the cash I carry”。会变成“这是我的车和我携带的现金。”
    • 我明白了,你是对的!这很棘手!您可以做的是,从您的字符串 (string.replace()) 中删除所有 +"*ç%&/(),然后使用您的正则表达式查找这些单词。Microsoft 有一篇关于 regex.escape msdn.microsoft.com/en-us/library/… 的文章也可能有帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-08
    • 2021-08-05
    • 2019-10-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多