VBA 正则表达式 - 匹配所有非字母数字字符,但忽略空格



我正在寻找一个正则表达式来消除标点符号和特殊字符。有没有办法让正则表达式匹配\W并忽略空格?

我有一个 VBA 脚本可以正常工作(如有必要,我很乐意分享(,但我认为我只是缺少一些简单的东西。当我运行代码时,它肯定有效,但 strPattern = "\W" 也在抓取空格。我知道我可以使用 \S 选项,但我似乎无法让它执行 AND,可以这么说。

法典:

Sub RegEx_Pattern_Removal()
Dim strPattern As String: strPattern = "W"
Dim strReplace As String: strReplace = ""
Dim regEx As New RegExp
Dim strInput As String
Dim myRange As Range
'Application.ScreenUpdating = False
Set myRange = Application.Selection
With regEx
.Global = True
.MultiLine = True
.IgnoreCase = False
.Pattern = strPattern
End With
For Each Cell In myRange
If Cell.Value <> Empty Then
strInput = Cell.Value
If regEx.Test(strInput) = True Then
Cell.Value = regEx.Replace(strInput, strReplace)
MsgBox "It's a match, baby!"
Else
MsgBox "No Match! Or... you fucked up"
End If
End If
Next
'Application.ScreenUpdating = True
End Sub

链接上道具的@slai

这是要使用的更简洁的模式之一:

strPattern = "[^dA-Za-z xa0]*"

对于仍然存在的"神秘空间",它实际上是一个硬空间,可以通过十六进制格式识别为\xa0,在模式的末尾看到。

这种模式正是我所需要的。

相关内容

最新更新