我正在尝试从字符串中提取广告尺寸。广告尺寸均为设定的标准尺寸。因此,虽然我更喜欢有一个正则表达式来查找模式,即 3 个数字后跟 2 或 3 个数字,但硬编码它也可以工作,因为我们知道大小是什么。以下是一些广告尺寸的示例:
300x250
728x90
320x50
我能够找到一些我修改过的 VBScript 几乎可以工作,但是因为我正在搜索的字符串不一致,所以在某些情况下它会拉动太多。例如:
![enter image description here](https://i.stack.imgur.com/fhIzS.jpg)
您会发现它在每个实例中都无法正确匹配。
我发现的 VB 代码实际上匹配除广告尺寸之外的所有内容。我对 VBScript 的了解不够,无法将其反转为仅查找广告尺寸并拉出它们。因此,它会查找所有其他文本并将其删除。
代码如下。有没有办法修复正则表达式,使其只返回广告尺寸?
Function getAdSize(Myrange As Range) As String
Dim regEx As New RegExp
Dim strPattern As String
Dim strInput As String
Dim strReplace As String
Dim strOutput As String
strPattern = "([^300x250|728x90])"
If strPattern <> "" Then
strInput = Myrange.Value
strReplace = ""
With regEx
.Global = True
.MultiLine = True
.IgnoreCase = True
.Pattern = strPattern
End With
If regEx.Test(strInput) Then
getAdSize = regEx.Replace(strInput, strReplace)
Else
getAdSize = "Not matched"
End If
End If
End Function
请注意,数据前面并不总是带有下划线,有时前后有一个破折号或空格。
EDIT:因为它实际上不是下划线分隔的,所以我们不能使用Split
。然而,我们可以迭代字符串并提取“#x#“手动。我已更新代码以反映这一点并验证其是否成功运行。
Public Function ExtractAdSize(ByVal arg_Text As String) As String
Dim i As Long
Dim Temp As String
Dim Ad As String
If arg_Text Like "*#x#*" Then
For i = 1 To Len(arg_Text) + 1
Temp = Mid(arg_Text & " ", i, 1)
If IsNumeric(Temp) Then
Ad = Ad & Temp
Else
If Temp = "x" Then
Ad = Ad & Temp
Else
If Ad Like "*#x#*" Then
ExtractAdSize = Ad
Exit Function
Else
Ad = vbNullString
End If
End If
End If
Next i
End If
End Function
使用 Select Case 布尔逻辑而不是嵌套 If 语句的同一函数的替代版本:
Public Function ExtractAdSize(ByVal arg_Text As String) As String
Dim i As Long
Dim Temp As String
Dim Ad As String
If arg_Text Like "*#x#*" Then
For i = 1 To Len(arg_Text) + 1
Temp = Mid(arg_Text & " ", i, 1)
Select Case Abs(IsNumeric(Temp)) + Abs((Temp = "x")) * 2 + Abs((Ad Like "*#x#*")) * 4
Case 0: Ad = vbNullString 'Temp is not a number, not an "x", and Ad is not valid
Case 1, 2, 5: Ad = Ad & Temp 'Temp is a number or an "x"
Case 4, 6: ExtractAdSize = Ad 'Temp is not a number, Ad is valid
Exit Function
End Select
Next i
End If
End Function
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)