You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从目标字符串中提取相乘数字并规范化输出格式?

提取字符串中相乘关系数字的解决方案

需求说明

需要从给定字符串中提取存在相乘关系的数字,规则如下:

  • 乘法符号支持x或*,不区分大小写
  • 数字可能带有英寸符号(双引号"或两个单引号''),也可能不带
  • 乘法符号与数字之间可能有空格,也可能没有

原GetNumeric函数会提取字符串中所有数字并拼接,无法识别相乘关系的数字序列,不符合需求。

示例对照

当前字符串预期结果
XX 2" * 3" RRR2x3
BBB 2"*3" HHH2x3
MMMM 235 FF EE2x3x5
RTE 2*3 EE XX2x3
AAA 4.5 x 5'' ERT EE4.5x5
XX 4''x5'' XX XX4x5
WWW 4''x 3.5 WWW4x3.5
EEE 4*5 NN4x5

原有函数代码

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

逻辑说明

  1. 正则表达式定位字符串中连续的相乘序列,覆盖数字、英寸符号、乘法符及空格的各种组合
  2. 移除所有英寸符号(双引号和两个单引号)
  3. 清理乘法符前后的多余空格,确保格式紧凑
  4. 将所有*替换为统一的x,输出符合预期的结果

内容的提问来源于stack exchange,提问作者Waleed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 09:25:01