在这样的句子中:
“[x]阿尔法
[33] 贝塔”
我提取一组括号内的数据作为 ([x], [33])
使用 VBA 正则表达式模式:
"(\[x\])|(\[\d*\])"
我无法直接将未括起来的数据数组提取为 (x, 33)
使用网络资源建议进行模式
"(?<=\[)(.*?)(?=\])"
这是 VBA 特定问题吗(即对其 Regex 实现的限制)
或者我是否误解了“向前和向后”的模式?
Public Function Regx( _
ByVal SourceString As String, _
ByVal Pattern As String, _
Optional ByVal IgnoreCase As Boolean = True, _
Optional ByVal MultiLine As Boolean = True, _
Optional ByVal MatchGlobal As Boolean = True) _
As Variant
Dim oMatch As Match
Dim arrMatches
Dim lngCount As Long
' Initialize to an empty array
arrMatches = Array()
With New RegExp
.MultiLine = MultiLine
.IgnoreCase = IgnoreCase
.Global = MatchGlobal
.Pattern = Pattern
For Each oMatch In .Execute(SourceString)
ReDim Preserve arrMatches(lngCount)
arrMatches(lngCount) = oMatch.Value
lngCount = lngCount + 1
Next
End With
Sub testabove()
Call Regx("[x] Alpha" & Chr(13) & _
"[33] Beta", "(\[x\])|(\[\d*\])")
End Sub
使用捕获子模式来获取所需的值。
Use
"\[(x)\]|\[(\d*)\]"
(or \d+
如果您需要匹配至少 1 位数字,如*
means 零次或多次出现, and +
means 一次或多次出现).
或者,使用要提取的通用模式anything方括号内无括号:
"\[([^\][]+)]"
然后,访问右侧Submatches
通过检查子匹配长度来索引(因为您有一个交替,所以任何一个子匹配都将为空),然后就可以了。只需改变你的for
循环与
For Each oMatch In .Execute(SourceString)
ReDim Preserve arrMatches(lngCount)
If Len(oMatch.SubMatches(0)) > 0 Then
arrMatches(lngCount) = oMatch.SubMatches(0)
Else
arrMatches(lngCount) = oMatch.SubMatches(1)
End If
' Debug.Print arrMatches(lngCount) ' - This outputs x and 33 with your data
lngCount = lngCount + 1
Next
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)