使用DOTNET REGEX匹配正确转义的引号

klu*_*msy 0 .net regex powershell

我有一种情况,我可以避免将用户提供的字符串注入我的PowerShell代码.虽然我确实有代码正确地逃避它(复制每个引用,powershell与单引号字符串接受5个不同的引用字符,包括智能引号,让我们现在让我们假设它接受'我想要做的是有一个正则表达式告诉我是否正确转义字符串,并通过将引号加倍,如下所示的字符串来完成转义

hello ' there
Run Code Online (Sandbox Code Playgroud)

很糟糕

hello '' there
Run Code Online (Sandbox Code Playgroud)

是安全的

然而,3个引号(或5或7等)也是如此

hello ''' there
Run Code Online (Sandbox Code Playgroud)

也很危险

所以我试图找到一个可以验证字符串是否被正确转义的正则表达式,因为没有奇数编号的单引号模式.

我知道使用标准正则表达式计数组是不可能的,但是对于dotnet捕获组我希望做这样的事情.

('\b(?<DEPTH>)|\b'(?<-DEPTH>)|[^']*)*(?(DEPTH)(?!))
Run Code Online (Sandbox Code Playgroud)

但我无法让它发挥作用.

Jay*_*kul 6

只是因为是你,@ klumsy:

"(?ix:                 # ignore whitespace and comments
    ^                  # start at the beginning
    (?(D)              # if 'D' is defined...
        (?<-D>')       #    match a quote and undefine D
        |              # otherwise
        (?:
            (?<D>')    #    match a quote and define D
            |
            [^']       #    or match anything else
            )
    )+                 # as many times as we can
    (?(D)              # if 'D' is STILL defined...
        ($!)           #    then don't match
        |              # otherwise
        [^']*          #    match anything except '
    )$                 # all the way to the end
)"
Run Code Online (Sandbox Code Playgroud)

这将仅匹配那些始终具有成对引号的字符串,但不匹配那些出现单引号或奇数引号''的字符串.据我所知,只适用于.Net正则表达式.

当然,只要删除所有空格和注释,就可以省略第一行和最后一行.