3

可能是这个问题真的很困惑,但我被卡住了。如何cl-ppcre:regex-replace-all替换反斜杠?

例如,我只想转义一些字符,如 '" ( ) 等,所以我将首先使用 | 替换,以查看匹配是否正常:

    CL-USER> (princ (cl-ppcre:regex-replace-all "(['\\(\\)\"])"
"foo \"bar\" 'baz' (test)" "|\\1"))
    PRINTED: foo |"bar|" |'baz|' |(test|)

好的,让我们放斜线:

    CL-USER> (princ (cl-ppcre:regex-replace-all "(['\\(\\)\"])"
"foo \"bar\" 'baz' (test)" "\\\1"))
    PRINTED: foo "bar" 'baz' (test) ;; No luck

不,我们需要两个斜线:

    CL-USER> (princ (cl-ppcre:regex-replace-all "(['\\(\\)\"])"
"foo \"bar\" 'baz' (test)" "\\\\1"))
    PRINTED: foo \1bar\1 \1baz\1 \1test\1 ;; Got slash, but not \1

也许像这样?

(princ (cl-ppcre:regex-replace-all "(['\\(\\)\"])"
"foo \"bar\" 'baz' (test)" "\\\{1}"))
PRINTED: foo "bar" 'baz' (test) ;; Nope, no luck here

当然,如果我在斜杠之间加空格,一切都可以,但我不需要它

(princ (cl-ppcre:regex-replace-all "(['\\(\\)\"])"
"foo \"bar\" 'baz' (test)" "\\ \\1"))
PRINTED: foo \ "bar\ " \ 'baz\ ' \ (test\ )

那么,我该如何写才能被foo \"bar\" \'baz\' \(test\)打印?谢谢。

4

2 回答 2

6

六源斜线

CL-USER> (princ (cl-ppcre:regex-replace-all "(['\\(\\)\"])"
                                            "foo \"bar\" 'baz' (test)"
                                            "\\\\\\1"))
foo \"bar\" \'baz\' \(test\)

当您在源代码中编写字符串时,每个斜杠都被用作转义符。您希望替换文本是字符序列\\1。要对替换中的第一个斜线进行编码(因为 CL-PPCRE 将处理斜线),CL-PPCRE 需要查看字符序列\\\1。前两个斜杠对斜杠进行编码,第三个对组号进行编码。要将该字符序列作为 Lisp 字符串,您必须编写"\\\\\\1".

于 2014-08-25T15:00:14.730 回答
1

迟到的答案,但对于其他人,请注意,在这种情况下,您最好避免使用字符串:

(cl-ppcre:regex-replace-all '(:register (:char-class #\' #\( #\) #\"))
                            "foo \"bar\" 'baz' (test)"
                            '("\\" 0))
于 2015-10-09T21:21:19.740 回答