gpt4 book ai didi

regex - 转义 [] 的正则表达式是什么?

转载 作者:行者123 更新时间:2023-12-04 07:52:10 27 4
gpt4 key购买 nike

我正在尝试匹配方括号,即 excel 中正则表达式 VBA 中的 []。我正在尝试使用以下代码,但它不起作用。

 Public Function IsSpecial(s As String) As Long
Dim L As Long, LL As Long
Dim sCh As String
IsSpecial = 0
For L = 1 To Len(s)
sCh = Mid(s, L, 1)
If sCh Like "[0-9a-zA-Z/;@%,'‚.+&/\(): ]" Or sCh = "_" Or sCh Like "[-]" Or sCh Like "\[" Then
Else
IsSpecial = 1
Exit Function
End If
Next L
End Function

最佳答案

根据 Using the Like operator and wildcard characters in string comparisons :

You can use a group of one or more characters (charlist) enclosed in brackets ([ ]) to match any single character in expression, and charlist can include almost any characters in the ANSI character set, including digits. You can use the special characters opening bracket ([), question mark (?), number sign (#), and asterisk (*) to match themselves directly only if enclosed in brackets. You cannot use the closing bracket (]) within a group to match itself, but you can use it outside a group as an individual character.


所以,你需要使用
Ch Like "[[]"
但是,您拥有的函数没有遵循您的逻辑,因为它单独检查每个字符,并且您希望确保 []被检查为字符序列。
使用正则表达式,它看起来像
Public Function IsSpecial(s As String) As Long
Dim L As Long, LL As Long
Dim rx As New regExp
rx.Pattern = "^(?:[0-9a-zA-Z/;@%,'‚.+&/\\(): _-]|\[])*$"
IsSpecial = 0
If Not rx.Test(s) Then IsSpecial = 1
End Function

关于regex - 转义 [] 的正则表达式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66902488/

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