搜索并替换不仅可以用空格分隔的整个单词 [英] Search and replace whole words which can be separated not only by a space
本文介绍了搜索并替换不仅可以用空格分隔的整个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找一种搜索和替换整个单词的方法。整个单词不仅可以用空格分隔,还可以用.、;:/?等等
我想做这样的事情
replace([address], ***--list of separators, like .,;:/?--*** & [replacewhat] & ***--list of separators, like .,;:/?--*** ," " & [replacewith] & " ")
我不知道如何传递分隔符列表,而不是为每个分隔符组合运行一次替换函数(加上我要替换的300个单词,查询的数量将达到惊人的数量)。
推荐答案
您可以使用要替换的单词前后带有标记(表示单词边界)的模式,使用正则表达式进行替换。
Public Function RegExpReplaceWord(ByVal strSource As String, _
ByVal strFind As String, _
ByVal strReplace As String) As String
' Purpose : replace [strFind] with [strReplace] in [strSource]
' Comment : [strFind] can be plain text or a regexp pattern;
' all occurences of [strFind] are replaced
' early binding requires reference to Microsoft VBScript
' Regular Expressions:
'Dim re As RegExp
'Set re = New RegExp
' with late binding, no reference needed:
Dim re As Object
Set re = CreateObject("VBScript.RegExp")
re.Global = True
're.IgnoreCase = True ' <-- case insensitve
re.pattern = "" & strFind & ""
RegExpReplaceWord = re.Replace(strSource, strReplace)
Set re = Nothing
End Function
如前所述,搜索区分大小写。如果希望不区分大小写,请启用此行:
re.IgnoreCase = True
在"即时"窗口中.
? RegExpReplaceWord("one too three", "too", "two")
one two three
? RegExpReplaceWord("one tool three", "too", "two")
one tool three
? RegExpReplaceWord("one too() three", "too", "two")
one two() three
? RegExpReplaceWord("one too three", "to", "two")
one too three
? RegExpReplaceWord("one too three", "t..", "two")
one two three
..。和您的分隔符范围.
? RegExpReplaceWord("one.too.three", "too", "two")
one.two.three
? RegExpReplaceWord("one,too,three", "too", "two")
one,two,three
? RegExpReplaceWord("one;too;three", "too", "two")
one;two;three
? RegExpReplaceWord("one:too:three", "too", "two")
one:two:three
? RegExpReplaceWord("one/too/three", "too", "two")
one/two/three
? RegExpReplaceWord("one?too?three", "too", "two")
one?two?three
? RegExpReplaceWord("one--too--three", "too", "two")
one--two--three
? RegExpReplaceWord("one***too***three", "too", "two")
one***two***three
这篇关于搜索并替换不仅可以用空格分隔的整个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文