VBA Regex -使用\b并在单词边界末尾包含“-”

wfveoks0  于 2023-01-21  发布在  其他
关注(0)|答案(1)|浏览(106)

我不熟悉VBA中的regex,但必须调试别人编写的代码。
我知道\b根据单词边界匹配位置,并排除了像-这样的非单词字符。
但是,我需要代码来匹配某些字符串中的-
例如,
匹配search_criteria中的cats and dogsi have cats and dogs,代码为:

"\b" & search_criteria & "\b"

工作。
但是,这并不匹配:
search_criteria中的dogs -dogs - sleeping
不起作用。
search_criteria是一个列表,其中包含不以-结尾的字符串和以-结尾的字符串。
就像这样:

dogs -  
cats -   
cats and dogs  
houses  
cars  
work -

我基本上必须更改代码末尾的\b,但需要帮助:

"\b" & search_criteria & "\b"
isr3a4wc

isr3a4wc1#

当你需要 adaptive word boundaries(我更喜欢使用这个术语)时,就需要这样做,因为你的所有术语都是以一个word char开头的,所以你可以继续使用\b作为左边的边界。
右边的边界是\b(如果最后一个字符是单词字符)或者 * 根本不检查边界 *,因为您不关心-后面是单词字符还是非单词字符。
可以使用正则表达式转义函数,如

Function RegexEscape(text As String) As String
Dim rx As New regExp
With rx
    .pattern = "[-\\^$*+?.()|[\]{}]"
    .Global = True
    .MultiLine = False
End With
RegexEscape = rx.Replace(text, "\$&")
End Function

然后将其与自适应单词边界一起使用

.pattern = "(?!\B\w)" & RegexEscape(search_criteria)  & "(?!\B\w)"

传统答案

也可以“手动”构建边界:

Function BuildBoundaryPattern(pattern As String) As String
BuildBoundaryPattern = "\b" & pattern
If Right(pattern, 1) Like "[a-zA-Z0-9_]" Then
    BuildBoundaryPattern = BuildBoundaryPattern & "\b"
End If
End Function

这将为每个检查构建正确的模式。
参见测试子组件:

Sub TestBBP()
Dim vbRegX As Object, vbRegXMatch As Object, pattern As String
Dim arr() As String: arr = Split("dogs -,cats -,cats and dogs,houses,cars,work -", ",")

For x = 0 To UBound(arr)
  Set vbRegX = New regExp
  vbRegX.pattern = BuildBoundaryPattern(arr(x))
  If vbRegX.Test(arr(x) & " sleeping") Then
    Debug.Print ("'" & arr(x) & "' in '" & arr(x) & " sleeping' matched!")
  End If
  If vbRegX.Test(arr(x) & "Sleeping") Then
    Debug.Print ("'" & arr(x) & "' in '" & arr(x) & " sleeping' matched!")
  End If
  Debug.Print ("------")
Next x
End Sub

输出:

'dogs -' in 'dogs - sleeping' matched!
'dogs -' in 'dogs - sleeping' matched!
------
'cats -' in 'cats - sleeping' matched!
'cats -' in 'cats - sleeping' matched!
------
'cats and dogs' in 'cats and dogs sleeping' matched!
------
'houses' in 'houses sleeping' matched!
------
'cars' in 'cars sleeping' matched!
------
'work -' in 'work - sleeping' matched!
'work -' in 'work - sleeping' matched!
------

相关问题