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

为字符串中相乘数字添加双引号的实现需求及正则函数优化问询

为乘法表达式添加双引号的VBA实现

需求说明

需要为字符串中以x、X或*作为运算符的乘法数字添加双引号",具体规则可参考以下示例:

当前字符串预期结果
string 2 x 3 stringstring 2"x3" string
string 2X3" stringstring 2"X3" string
string 235 stringstring 2"*3"*5" string
string 2"*3 stringstring 2"*3" string
string 4.5 x 5 stringstring 4.5"x5" string
string 4"x5" stringstring 4"x5" string
string 4x 3.5" stringstring 4"x3.5" string

现有提取函数代码

Option Explicit
Option Compare Text

Function RegexExtractt(str, Optional pos As Integer = 0) As String
    
    Static re As Object
    If re Is Nothing Then Set re = CreateObject("vbscript.regexp")
    
    re.Pattern = "\d+(?:\.\d+)?(?:''|""|in(?:ch)?\b)?(?:\s*[*x]\s*\d+(?:\.\d+)?(?:''|""|in(?:ch)?\b)?)*\s*[*x]\s*\d+(?:\.\d+)?"
    re.Global = False
    re.IgnoreCase = True
    
    If re.test(str) Then
        RegexExtractt = re.Execute(str)(pos)
    Else
        RegexExtractt = vbNullString
    End If

End Function 

实现添加双引号的函数

基于正则匹配替换的思路,编写AddQuotesToMultiplication函数完成需求:

Option Explicit
Option Compare Text

Function AddQuotesToMultiplication(inputStr As String) As String
    Static re As Object
    If re Is Nothing Then
        Set re = CreateObject("vbscript.regexp")
        ' 匹配数字(含小数)+ 运算符(x/X/*)+ 数字(含小数)的组合,兼容已有引号和空格
        re.Pattern = "(\d+(?:\.\d+)?)([""']?)\s*([xX*])\s*(\d+(?:\.\d+)?)([""']?)"
        re.Global = True
        re.IgnoreCase = True
    End If
    
    ' 替换规则:保留原有数字和引号,在运算符前后补充双引号
    AddQuotesToMultiplication = re.Replace(inputStr, "$1$2""$3$4""")
End Function

逻辑说明

  1. 正则模式拆解:
    • (\d+(?:\.\d+)?):捕获第一个数字(支持小数格式)
    • ([""']?):捕获第一个数字可能已有的引号(可选匹配)
    • \s*([xX*])\s*:捕获乘法运算符,允许前后存在任意空格
    • (\d+(?:\.\d+)?):捕获第二个数字(支持小数格式)
    • ([""']?):捕获第二个数字可能已有的引号(可选匹配)
  2. 替换逻辑:
    保留原有数字和已存在的引号,在运算符前添加一个双引号,运算符后数字末尾添加一个双引号,避免重复添加引号的同时完成需求。

验证效果

将示例字符串传入该函数,可得到预期结果:

  • 输入string 2*3*5 string → 输出string 2"*3"*5" string
  • 输入string 4"x5" string → 输出string 4"x5" string(已有引号的组合不会重复添加)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 01:08:11