正则表达式筛选Eclass字符串的技术问题求助
正则表达式修正方案(VBA)
问题1:让re仅匹配无后续内容的目标格式
原正则\@[0-9]\|[0-9][0-9]\|[0-9][0-9]\|[0-9][0-9]会匹配字符串中包含该格式的任意内容,比如@1|27|23|02|01|06180704的前半段符合格式,所以返回True。要限制为整个字符串完全匹配该格式,需添加字符串边界标记:
^:匹配字符串开头$:匹配字符串结尾
修改后的re正则Pattern:
.Pattern = "^\@[0-9]\|[0-9]{2}\|[0-9]{2}\|[0-9]{2}$"
(将[0-9][0-9]简化为[0-9]{2},逻辑一致且更简洁)
问题2:re2无法匹配目标字符串的原因
目标字符串@1|27|23|02|01|06180704的结构是:@数字|两位数字|两位数字|两位数字|两位数字|7-8位数字,但原re2的Pattern漏掉了倒数第二段的两位数字(即01对应的部分),同时缺少字符串边界标记,导致无法完全匹配。
修改后的re2正则Pattern:
.Pattern = "^\@[0-9]\|[0-9]{2}\|[0-9]{2}\|[0-9]{2}\|[0-9]{2}\|[0-9]{7,8}$"
修正后的完整VBA函数
Function ColumnValue(RefColObject, ColumnObject, BaseRowIndex, BaseColumnIndex) Dim SAPString As String Dim re As RegExp, re2 As RegExp SAPString = RefColObject.SystemFullName 'MsgBox SAPString '可根据需要保留调试弹窗 Set re = New RegExp With re .Pattern = "^\@[0-9]\|[0-9]{2}\|[0-9]{2}\|[0-9]{2}$" .IgnoreCase = False .Global = False End With Set re2 = New RegExp With re2 .Pattern = "^\@[0-9]\|[0-9]{2}\|[0-9]{2}\|[0-9]{2}\|[0-9]{2}\|[0-9]{7,8}$" .IgnoreCase = False .Global = False End With If re2.Test(SAPString) Then MsgBox "Mit SAP" ElseIf re.Test(SAPString) Then MsgBox "Nur Pfad" End If Set re = Nothing Set re2 = Nothing '补充释放第二个正则对象 End Function
内容的提问来源于stack exchange,提问作者Luca
相关产品推荐
相关产品推荐

