从仅与正则表达式模式匹配的字符串中提取字符

问题描述 投票:0回答:1

我正在研究一个宏,以自动将电子表格数据重新格式化为可以上传到广告服务器的导入表。

我正在导入具有严格命名约定的展示位置,仅允许以下字符:

a-z A-Z 0-9 _ + / \ - ( ) . : « » ~

我想查看代表展示位置名称的字符串,并替换上面找不到的任何字符。

因此,如果我的展示位置名称是:

apples?orange's*pears(300x250)

我希望结果看起来像:

applesorangespears(300x250)

这是我目前拥有的:

 'test string
 placement_name = "test*123?test'456(300x250)"

'Allowed characters
regex_pattern = "a-zA-Z0-9_+/\\-().:«»~"

 If regex_pattern <> "" Then
    With regex
        .Global = True
        .Pattern = regex_pattern
    End With

    'Execute RegEx pattern on placement name
    Set regex_matches = regex.Execute(placement_name)

    If regex_matches.count > 0 Then
        For i = 0 To regex_matches.count - 1
            placement_name = regex_matches.Item(i).Value
        Next i
    End If
End If

但是当我运行它时,它将返回完整的展示位置名称,并且不会删除在正则表达式中找不到的字符。

有人可以提供任何指导来帮助我吗?我可以使用伪代码甚至是口头建议。

谢谢!

regex excel vba
1个回答
0
投票
Dim RegEx As Object
sStr = "apples?orange's*pears(300x250)"

Set RegEx = CreateObject("VBScript.RegExp")
RegEx.Global = True

RegEx.Pattern = "[^a-zA-Z0-9-\\().:«»~-]"

Debug.Print RegEx.replace(sStr, "")

您可以更改RegEx模式以适合我错过的情况。

© www.soinside.com 2019 - 2024. All rights reserved.