如何删除两个string之间的文本,包括标识符?

我有一个要求删除两个string之间的文本。
文本的一个例子是:

Abc%678x”cv ","@metadata":{abxkl "DataArray"}},{"columnName":" 

要求是从,"@met until "}开始删除文本

要求是使用,"@met"}作为开始和结束标识符,并删除它们之间的文本,包括标识符。

文件中可能有多个此开始和结束标识符。

输出应该是这样的:

 Abc%678x”cv "},{"columnName":" 

如何编写Excel公式或简单的VBA脚本来删除两个string之间的文本,包括标识符?

式:

 =LEFT(A1,FIND(",""@met",A1)-1)&RIGHT(A1,LEN(A1)-FIND("}",A1,FIND("""@met",A1))) 

VBAfunction:

 Function RemoveBetweenSeparators( _ ByVal MyString As String, _ ByVal SepL As String, _ ByVal SepR As String) _ As String Dim sL As String Dim sR As String sL = Split(MyString, SepL)(0) sR = Replace(MyString, sL, "") sR = Replace(sR, Split(sR, SepR)(0) & SepR, "") RemoveBetweenSeparators = sL & sR End Function 

可以这样使用:

 =RemoveBetweenSeparators(A1,"""@meta","}") 

编辑:我也错过了“多次发生”的要求,第一次! 这使得它有点棘手,但试试这个:

 Function RemoveBetweenSeparatorsMultiple( _ ByVal MyString As String, _ ByVal SepL As String, _ ByVal SepR As String) _ As String Dim sOut As String Dim sL As String Do Until InStr(MyString, SepL) = 0 sL = Split(MyString, SepL)(0) sOut = sOut & sL MyString = Replace(MyString, sL & SepL, "", 1, 1) sL = Split(MyString, SepR)(0) MyString = Replace(MyString, sL & SepR, "", 1, 1) Loop RemoveBetweenSeparatorsMultiple = sOut & MyString End Function 

也许是这样的东西(虽然没有testing!):

  Function cleanedStr (inpStr as String; beginDel as string; endDel as Str) as String Dim idx as long Dim take as boolean Dim outStr as String Dim myCh as String take = true outStr = "" for idx = 1 to len(inpStr) myCh = mid(inpStr, idx, 1) if myCh = beginDel then take = false if take then outStr = outStr & myCh else if myCh = endDel then take = true end if next idx cleanedStr = outStr end Function 

注意,开始标识符只有1个字符。
beginDel将@和endDel会}

我的道歉,没有注意到可能有多次发生。 我稍后会编辑我的答案。

假设原始文本存储在A1中。

A2=LEFT(A1,FIND(",""@met",A1)-1)&RIGHT(A1,LEN(A1)-FIND("""}",A1)-1)

注意:如果您需要强制excel将双引号标记为正常文本,则必须键入两个"代表a "

如果可能有多个出现,请尝试此操作

 Private Function RemoveText(ByVal tgtString As String, ByVal StartText As String, ByVal EndText As String) As String Do While InStr(1, tgtString, StartText) > 0 tgtString = Left(tgtString, InStr(1, tgtString, StartText) - 1) & Right(tgtString, Len(tgtString) - InStr(1, tgtString, EndText) - 1) Loop RemoveText = tgtString End Function Private Sub test() 'remove certain string in A1 and store the result in A2 Range("A2").Value = RemoveText(Range("A1").Value, ",""@met", """}") End Sub 

这可以使用VBA和正则expression式轻松完成:

 Option Explicit Function RemoveBetweenDelimiters(S As String) As String Dim RE As Object Set RE = CreateObject("vbscript.regexp") With RE .Global = True .ignorecase = True .Pattern = ",""@met[^}]+}" RemoveBetweenDelimiters = .Replace(S, "") End With End Function 

正则expression式的解释:

,“@满足[^}] +}

 ,"@met[^}]+} 

选项:不区分大小写; 换行符$ ^

  • 匹配string“,”@ met“字面意思 ,"@met
  • 匹配任何不是“}” [^}]+ 字符
    • 在一次和无限次之间,尽可能多的次数,根据需要回馈(贪婪) +
  • 匹配字符“}”字面上 }

用RegexBuddy创build