gpt4 book ai didi

regex - 如何使用 excel 正则表达式从字符串中提取广告尺寸

转载 作者:行者123 更新时间:2023-12-04 21:21:18 32 4
gpt4 key购买 nike

我正在尝试从字符串中提取广告尺寸。广告尺寸都是设置的标准尺寸。因此,虽然我更喜欢寻找模式的正则表达式,IE 3 数字后跟 2 或 3 个数字,但硬编码它也可以工作,因为我们知道大小是多少。以下是一些广告尺寸的示例:

300x250

728x90

320x50

我能够找到一些我修改过的几乎可以工作的 VBScript,但是因为我正在搜索的字符串不一致,所以在某些情况下它拉得太多了。例如:

enter image description here

您会看到它在每个实例中都没有正确匹配。

我发现的 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

请注意,数据并不总是以下划线开头,有时它是一个破折号或前后的空格。

最佳答案

编辑:因为它实际上不是下划线分隔的,所以我们不能使用 Split .然而,我们可以遍历字符串并手动提取“#x#”。我已经更新了代码以反射(reflect)这一点并验证它可以成功运行。

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 bool 逻辑而不是嵌套 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

关于regex - 如何使用 excel 正则表达式从字符串中提取广告尺寸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48427343/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com