获取字符串中两个字符之间的值 [英] get value between two characts in string
本文介绍了获取字符串中两个字符之间的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要一个字符串中两个字符之间的值.这些值在{和}之间.有时可能会发生1次以上.
I need a value between two characters in a string.The values are between { and }. Sometimes there may be more then 1 occurrence.
var = split("this {is} a {test}","{")
var = split("this {is} a {test}","}")
推荐答案
我不认为拆分字符串会是一个解决方案,因为您需要知道拆分字符串的字符的位置.
I don't believe that splitting the string would be a solution since you need to know the position of the character that is splitting your string.
所以我给你两个解决方案
So I'm giving you two solutions
首先,您需要添加对VBA正则表达式的引用. Tool -> References & Microsoft VBScript Regular Expression 5.5
First of all, you'll need to add the reference to VBA Regular Expression. Tool -> References & Microsoft VBScript Regular Expression 5.5
Sub Test1()
Dim sText As String
Dim oRegExp As RegExp
Dim oMatches As MatchCollection
sText = "this {is} a {test}"
Set oRegExp = New RegExp
With oRegExp
oRegExp.IgnoreCase = True
oRegExp.Pattern = "{([^\}]+)"
oRegExp.Global = True
End With
Set oMatches = oRegExp.Execute(sText)
For Each Text In oMatches
Debug.Print Mid(Text, 2, Len(Text))
Next
End Sub
解决方案2
线性搜索
代码
Sub Test2()
Dim bIsBetween As Boolean
Dim iLength As Integer
Dim sText As String
Dim sToken As String
bIsBetween = False
sToken = ""
sText = "this {is} a {test}"
iLength = Len(sText) - 1
For I = 1 To iLength
Dim chr As String
Dim nextChr As String
chr = Mid(sText, I, 1)
nextChr = Mid(sText, I + 1, 1)
If (chr = "{") Then
bIsBetween = True
End If
If (nextChr = "}") Then
bIsBetween = False
End If
If (bIsBetween = True) Then
sToken = sToken & nextChr
Else
If (Len(sToken) > 0) Then
Debug.Print sToken
sToken = ""
End If
End If
Next I
End Sub
这篇关于获取字符串中两个字符之间的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文