如果我有一个字符串:"foo, bar" baz, test, blah
,我如何删除一个特定的逗号,即不是全部,而是我选择的一个?
使用Replace和INSTR看起来我不知道逗号在哪里。问题是,如果逗号出现在引号之间,我只想删除它。
所以,我可能想删除第一个逗号,但我可能不会。
更清楚地说,如果一组引号之间有逗号,我需要将其删除。如果没有,那就没什么可做的了。但是,我不能只删除所有逗号,因为我需要字符串中的其他逗号。
以这种方式尝试使用正则表达式:
Sub foo()
Dim TXT As String
TXT = """foo, bar"" baz, test, blah"
Debug.Print TXT
Dim objRegExp As Object
Set objRegExp = CreateObject("vbscript.regexp")
With objRegExp
.Global = True '
.Pattern = "(""\w+)(,)(\s)(\w+"")"
Debug.Print .Replace(TXT, "$1$3$4")
End With
End Sub
对于您提供的示例值,它按预期工作,但可能需要通过更改.Pattern
更复杂的文本进行额外调整。
编辑如果您想将此解决方案用作 Excel 函数而不是使用此代码:
Function RemoveCommaInQuotation(TXT As String)
Dim objRegExp As Object
Set objRegExp = CreateObject("vbscript.regexp")
With objRegExp
.Global = True
.Pattern = "(""\w+)(,)(\s)(\w+"")"
RemoveCommaInQuotation = .Replace(TXT, "$1$3$4")
End With
End Function
啊。这是另一种方式
Public Function foobar(yourStr As String) As String
Dim parts() As String
parts = Split(yourStr, Chr(34))
parts(1) = Replace(parts(1), ",", "")
foobar = Join(parts, Chr(34))
End Function
对奇数个双引号进行一些错误检查:
Function myremove(mystr As String) As String
Dim sep As String
sep = """"
Dim strspl() As String
strspl = Split(mystr, sep, -1, vbBinaryCompare)
Dim imin As Integer, imax As Integer, nstr As Integer, istr As Integer
imin = LBound(strspl)
imax = UBound(strspl)
nstr = imax - imin
If ((nstr Mod 2) <> 0) Then
myremove = "Odd number of double quotes"
Exit Function
End If
For istr = imin + 1 To imax Step 2
strspl(istr) = Replace(strspl(istr), ",", "")
Next istr
myremove = Join(strspl(), """")
End Function