Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/290.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 需要正则表达式专家:stringliteral中的圆括号_Python_Regex_Vba - Fatal编程技术网

Python 需要正则表达式专家:stringliteral中的圆括号

Python 需要正则表达式专家:stringliteral中的圆括号,python,regex,vba,Python,Regex,Vba,我正在使用正则表达式搜索字符串中的字符串。模式是以()结尾的字符串文字,例如 # pattern " before the bracket (" # string this text is before the bracket (and this text is inside) and this text is after the bracket 我知道如果我用反斜杠转义字符,模式将起作用,即: # pattern " before the bracket \\(" 但是模式字符串来自另一

我正在使用正则表达式搜索字符串中的字符串。模式是以
)结尾的字符串文字,例如

# pattern
" before the bracket ("

# string
this text is before the bracket (and this text is inside) and this text is after the bracket
我知道如果我用反斜杠转义字符,模式将起作用,即:

# pattern
" before the bracket \\("
但是模式字符串来自另一个搜索,我无法控制字符的位置。是否有办法转义整个字符串文字,以便将标记之间的任何内容视为字符串?例如:

# pattern
\" before the ("
我唯一的另一个选择是为每个受保护的字符添加转义


re.escape正是我所需要的。我在Access VBA中使用的regexp没有该方法。我只有replace、execute或test方法

在VBA中是否有一种方法可以转义字符串中的所有内容


谢谢

下面的正则表达式将捕获从字符串开头到第一个
)的所有内容。第一个捕获的组
$1
将包含
之前的部分

根据您的语言,您可能必须避免使用它,因为:

"^([^(]+)\\("

您没有指定语言,但它看起来像Python,因此如果Python中有一个字符串,需要转义其特殊正则表达式字符,请使用:


请注意,空格也是转义的(可能是为了确保它们仍然在
re.VERBOSE
regex中工作)。

可以编写自己的VBA转义函数:

Function EscapeRegEx(text As String) As String
    Dim regEx As RegExp
    Set regEx = New RegExp

    regEx.Global = True
    regEx.Pattern = "(\[|\\|\^|\$|\.|\||\?|\*|\+|\(|\)|\{|\})"

    EscapeRegEx = regEx.Replace(text, "\$1")
End Function

我很确定,由于VBA/VBScript中RegExp功能的限制,在使用它之前,您必须替换模式中的特殊字符。它似乎不像Python中那样内置任何东西。

当模式是常量字符串时,您不需要使用regex。他的模式不是常量字符串响铃。请重新阅读。我认为这不是问题的实际答案:正则表达式搜索的文本来自外部源,可能包含需要转义的字符,因为它们在正则表达式中有意义。确切地说,我需要在字符串中的每个字符前有效地插入\项。在正则表达式中如何做到这一点xp VBA?感谢您回来。我最后编写了一个包装器循环替换来转义所有特殊字符:公共函数转义(ByVal strString作为字符串)作为字符串Dim,作为新的RegExp Dim EscapeChars()作为变量EscapeChars=Array(“\\”、“*”、“\+”、“\?”、“\\\”、“\{”、“[”、“(”、”、“,”、“^、“\$”),用于索引=0到UBound(转义cars)re.Pattern=EscapeChars(Index)re.Global=True strString=re.Replace(strString,EscapeChars(Index))Next Escape=strString End function完美!正是我所需要的。谢谢!
>>> import re
>>> re.escape("Wow. This (really) is *cool*")
'Wow\\.\\ This\\ \\(really\\)\\ is\\ \\*cool\\*'
Function EscapeRegEx(text As String) As String
    Dim regEx As RegExp
    Set regEx = New RegExp

    regEx.Global = True
    regEx.Pattern = "(\[|\\|\^|\$|\.|\||\?|\*|\+|\(|\)|\{|\})"

    EscapeRegEx = regEx.Replace(text, "\$1")
End Function