如何从目标字符串中提取相乘数字并规范化输出格式?
提取字符串中相乘关系数字的解决方案
需求说明
需要从给定字符串中提取存在相乘关系的数字,规则如下:
- 乘法符号支持
x或*,不区分大小写 - 数字可能带有英寸符号(双引号
"或两个单引号''),也可能不带 - 乘法符号与数字之间可能有空格,也可能没有
原GetNumeric函数会提取字符串中所有数字并拼接,无法识别相乘关系的数字序列,不符合需求。
示例对照
| 当前字符串 | 预期结果 |
|---|---|
| XX 2" * 3" RRR | 2x3 |
| BBB 2"*3" HHH | 2x3 |
| MMMM 235 FF EE | 2x3x5 |
| RTE 2*3 EE XX | 2x3 |
| AAA 4.5 x 5'' ERT EE | 4.5x5 |
| XX 4''x5'' XX XX | 4x5 |
| WWW 4''x 3.5 WWW | 4x3.5 |
| EEE 4*5 NN | 4x5 |
原有函数代码
Function GetNumeric(CellRef As String) Dim StringLength As Long, i As Long, Result As Variant StringLength = Len(CellRef) For i = 1 To StringLength If IsNumeric(Mid(CellRef, i, 1)) Then Result = Result & Mid(CellRef, i, 1) End If Next i GetNumeric = Result End Function
正确实现方案
使用正则表达式匹配相乘序列,再清理格式得到统一结果:
Function GetMultiplicationNumbers(CellRef As String) As String Dim regEx As Object Dim match As Object Dim resultStr As String Set regEx = CreateObject("VBScript.RegExp") With regEx .Global = True .IgnoreCase = True ' 匹配包含数字、英寸符号、乘法符的连续相乘序列 .Pattern = "(\d+\.?\d*)\s*[""']*\s*[x*]\s*[""']*\s*(\d+\.?\d*)(?:\s*[""']*\s*[x*]\s*[""']*\s*(\d+\.?\d*))*" End With Set match = regEx.Execute(CellRef) If match.Count > 0 Then resultStr = match(0).Value ' 移除所有英寸符号 resultStr = Replace(Replace(resultStr, """", ""), "''", "") ' 清除乘法符周围的空格 resultStr = Replace(resultStr, " x ", "x") resultStr = Replace(resultStr, " * ", "*") resultStr = Replace(resultStr, "x ", "x") resultStr = Replace(resultStr, " x", "x") resultStr = Replace(resultStr, "* ", "*") resultStr = Replace(resultStr, " *", "*") ' 统一将*替换为x resultStr = Replace(resultStr, "*", "x") End If GetMultiplicationNumbers = resultStr End Function
逻辑说明
- 正则表达式定位字符串中连续的相乘序列,覆盖数字、英寸符号、乘法符及空格的各种组合
- 移除所有英寸符号(双引号和两个单引号)
- 清理乘法符前后的多余空格,确保格式紧凑
- 将所有
*替换为统一的x,输出符合预期的结果
内容的提问来源于stack exchange,提问作者Waleed
相关产品推荐
相关产品推荐

