VB 返回字符串中两个关键字中间字符
上次再写VB分析网页源代码中的URL的时候就用到,比如分析源代码中间所有url,url的格式是<a href="#">XXX</a>,url就在<a 和</a>中间,怎么得到呢。
考虑到普遍性,可以写一个function
'在字符串中查找位于关键字key1和关键字key2之间的字符串
'S 待分析的字符串
'Key1 关键字1
'Key2 关键字2 (key1不能和key2相同)
'L 关键字key1和关键字key2之间字符串的最大可能长度 但不能超过 Len(S)-Len(Key1)-Len(key2)的长度
'New_Str() 关键字key1和key2之间的字符串数组
Function GetStrInStrByKey(S As String, Key1 As String, Key2 As String, L As Long, ByRef New_Str() As String) As Integer
On Error GoTo E:
Dim i As Long
i = Len(S)
If i = 0 Or i < Len(Key1) + Len(Key2) Then
GetStrInStrByKey = 0
Exit Function
End If
Dim N As Integer
Dim index() As Long
N = inStr_n(S, Key1, index) ' 总共有N个关键字key1
Dim Temp As String
Dim Temp1 As Long
Dim M As Integer
For i = 0 To N - 1
Temp = Mid(S, index(i) + Len(Key1), L) '从第一个关键字key1开始,向后面数L长度的字符 (新得到的字符串前面去掉关键字key1)
ReDim Preserve New_Str(M) '数组元素增加一个
Temp1 = InStr(Temp, Key2)
If Temp1 <> 0 Then
New_Str(M) = Left(Temp, Temp1 - 1)
End If
M = M + 1
Next
GetStrInStrByKey = 1
Exit Function
E:
Debug.Print Err.Description
GetStrInStrByKey = 0
End Function
'S 待分析的字符串
'Key1 关键字1
'Key2 关键字2 (key1不能和key2相同)
'L 关键字key1和关键字key2之间字符串的最大可能长度 但不能超过 Len(S)-Len(Key1)-Len(key2)的长度
'New_Str() 关键字key1和key2之间的字符串数组
Function GetStrInStrByKey(S As String, Key1 As String, Key2 As String, L As Long, ByRef New_Str() As String) As Integer
On Error GoTo E:
Dim i As Long
i = Len(S)
If i = 0 Or i < Len(Key1) + Len(Key2) Then
GetStrInStrByKey = 0
Exit Function
End If
Dim N As Integer
Dim index() As Long
N = inStr_n(S, Key1, index) ' 总共有N个关键字key1
Dim Temp As String
Dim Temp1 As Long
Dim M As Integer
For i = 0 To N - 1
Temp = Mid(S, index(i) + Len(Key1), L) '从第一个关键字key1开始,向后面数L长度的字符 (新得到的字符串前面去掉关键字key1)
ReDim Preserve New_Str(M) '数组元素增加一个
Temp1 = InStr(Temp, Key2)
If Temp1 <> 0 Then
New_Str(M) = Left(Temp, Temp1 - 1)
End If
M = M + 1
Next
GetStrInStrByKey = 1
Exit Function
E:
Debug.Print Err.Description
GetStrInStrByKey = 0
End Function
[本日志由 田草 于 2008-03-01 09:13 PM 编辑]
|
暂时没有评论
发表评论 - 不要忘了输入验证码哦! |