用这样的句子:
“ [x] Alpha
[33] Beta”
我将一组带括号的数据提取为([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
在子模式周围使用捕获将获取所需的值。
使用
"\[(x)\]|\[(\d*)\]"
(或者,\d+
如果您需要匹配至少一位数字,则*
表示零次或多次出现,并且+
表示一次或多次出现)。
或者,使用通用模式提取没有方括号的方括号内的所有内容:
"\[([^\][]+)]"
然后,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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句