合并三个VBA正则函数以去除数字与X间的所有空格
合并VBA正则函数统一处理数字与x间的空格问题
数据库导出到Excel的用户输入值里,乘法格式不统一,数字和字符x之间的空格位置随机,比如:
- "3 x2"
- "4x 8"
- "6 x 10"
目前已编写三个分别处理不同情况的VBA函数且运行正常,但希望合并为单个函数简化使用。
预期转换效果
| 当前值 | 预期结果 |
|---|---|
| Last the 3 x2 Injection | Last the 3x2 Injection |
| Last the 4x 8 Injection | Last the 4x8 Injection |
| Last the 6 x 10 Injection | Last the 6x10 Injection |
现有三个VBA函数
Function Remove_Space_between_Digit_X(ByVal str As String) As String Static reg As New RegExp reg.Global = True reg.IgnoreCase = True reg.Pattern = "(\s[0-9]+)(\s)(x)" Remove_Space_between_Digit_X = re.Replace(str, "$1$3") End Function Function Remove_Space_between_X_Digit(ByVal str As String) As String Static reg As New RegExp reg.Global = True reg.IgnoreCase = True reg.Pattern = "(x)(\s)([0-9]+)(\s)" Remove_Space_between_X_Digit = reg.Replace(str, "$1$3$4") End Function Function Remove_Space_around_X_Digit(ByVal str As String) As String Static reg As New RegExp reg.Global = True reg.IgnoreCase = True reg.Pattern = "([0-9])+(\s)(x)(\s)([0-9]+)(\s)" Remove_Space_around_X_Digit = reg.Replace(str, "$1$3$5$6") End Function
合并后的解决方案
直接用一个正则表达式就能搞定所有情况,一次性去掉数字和x之间的所有空格。合并后的VBA函数如下:
Function RemoveSpacesAroundX(ByVal str As String) As String Static reg As New RegExp reg.Global = True reg.IgnoreCase = True ' 匹配数字、任意空格、x、任意空格、数字的组合 reg.Pattern = "(\d+)\s*x\s*(\d+)" ' 替换成无空格的数字x数字格式 RemoveSpacesAroundX = reg.Replace(str, "$1x$2") End Function
正则说明
(\d+):捕获前面的一串数字,存为分组1\s*:匹配数字和x之间的0个或多个空格x:匹配x字符(不区分大小写)- 第二个
\s*:匹配x和后面数字之间的0个或多个空格 - 第二个
(\d+):捕获后面的一串数字,存为分组2
不管是数字后带空格、x后带空格,还是两边都有空格,这个正则都能精准匹配并替换成紧凑的数字x数字格式,全局替换所有符合条件的内容,不用再拆三个函数。
内容的提问来源于stack exchange,提问作者hope
相关产品推荐
相关产品推荐

