Excel VBA 中的正则表达式不正确地匹配扩展 ASCII 字符

标签 regex excel vba vbscript non-printable

我正在尝试使用 Excel VBA 中的以下正则表达式删除所有不可打印和非 ASCII(扩展)字符:

[^\x09\0A\0D\x20-\xFF]

理论上,这应该匹配除制表符、换行符、回车符或可打印 ASCII 字符(十六进制 20 和 FF 或十进制 32 和 255 之间的字符代码)以外的任何字符。我已确认here Microsoft VBScript 正则表达式支持\xCC 表示法,其中 CC 是十六进制的 ASCII 代码。

问题是这个正则表达式匹配 127 以上的每个字符。然后,当匹配字符的代码高于 127 时,它会在 match.value 上抛出“无效过程调用”。是否只是 VBScript RegExes 不支持字符代码127以上?我似乎无法在任何地方找到这些数据。完整代码如下:

regEx.Pattern = "[^\x09\0A\0D\x20-\xFF]"
regEx.IgnoreCase = True 'True to ignore case
regEx.Global = True 'True matches all occurances, False matches the first occurance
regEx.MultiLine = True
If regEx.Test(Cells(curRow, curCol).Value) Then
    Set matches = regEx.Execute(Cells(curRow, curCol).Value)
    numReplacements = numReplacements + matches.Count
    For matchNum = matches.Count To 1 Step -1
        Cells(numReplacements - matchNum + 2, 16).Value = matches.Item(matchNum).Value
        Cells(numReplacements - matchNum + 2, 17).Value = Asc(matches.Item(matchNum).Value)
    Next matchNum
    Cells(curRow, curCol).Value = regEx.Replace(Cells(curRow, curCol).Value, replacements(pattNo))
End If

它匹配的第一个字符是 0x96 (&ndash)。当我观看“比赛”并展开它时,我可以在“观看”窗口中看到它。但是,当我尝试观看 matches.Item(matchNum).Value 时,我得到了(参见屏幕截图)。有什么想法吗?

最佳答案

Microsoft VBScript regular expressions support the \xCC notation where CC is an ASCII code in hexadecimal

请注意,ASCII 定义为从\x00 到\x7F,其中可打印的 ASCII 字符是从\x20 到\x7E。

代码\x80 及以上是 Ansi,而不是 ASCII。

下一步尝试:

Dim ii, sExPatern: sExPatern = "[^\x09\x0A\x0D\x20-\x7E\"
For ii = 128 To 255
  sExPatern = sExPatern & Chr( ii)
Next
sExPatern = sExPatern & "]"
'...
regEx.Pattern = sExPatern

老实说,我不确定某些代码的值(value),例如十进制的129, 131, 136, 144, 152, 160(我的Ansi代码页是“Windows Central Europe”,所以你可以考虑更详细的检查)

关于Excel VBA 中的正则表达式不正确地匹配扩展 ASCII 字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24149389/

相关文章:

vba - 使用MS Access组合框键入时进行搜索

ruby - 模式匹配时 =~ 和 match() 有什么区别?

Excel公式获取2个字符之间的字符串

Excel从固定单元格引用到列末尾?

excel - 在 Excel 中使用 VBA 选择从 A1 到文件末尾的范围

正则表达式从 VBA 中的字符串中提取数字

Excel 或 VBA 将非结构化文本转换为列

c# - "arbitrary"分隔符之间的 RegEx 替换

regex - 如何创建正则表达式来将平板电脑流量与移动流量分开?

java - 通过文本文件按特定顺序将 JMenuItems 从 ReGex 结果添加到 JMenu