繁体   English   中英

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

[英]Matching properly escaped quotes with DOTNET REGEX

我有一种情况可以避免将用户提供的字符串注入到我的PowerShell代码中。 虽然我确实已经对代码进行了正确的转义(复制每个引号,并且带单引号的字符串的powershell接受5个不同的引号字符,包括智能引号,但现在让我们假设它接受'我想做的就是让一个正则表达式告诉我字符串是否正确转义,并通过加倍引号完成转义,因此字符串如下

hello ' there

不好

hello '' there

是安全的

但是3个引号(或5或7等)也很糟糕

hello ''' there

也很危险

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

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

('\b(?<DEPTH>)|\b'(?<-DEPTH>)|[^']*)*(?(DEPTH)(?!))

但我无法使它正常工作。

只是因为是你,@ 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
)"

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

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

为什么不简单地用两个''代替一个':

> $a = read-host
foo ' bar
> $a
foo ' bar
> $a -replace "'","''"
foo '' bar

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM