regex - cl-ppcre:regex-replace 和反斜杠替换

标签 regex lisp common-lisp cl-ppcre

可能这个问题真的很傻,但我被卡住了。如何在 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\)?谢谢。

最佳答案

六个源斜线

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"

关于regex - cl-ppcre:regex-replace 和反斜杠替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25487352/

相关文章:

regex - 如果单元格包含特定文本,则返回特定的下拉列表项(Google 表格)

PHP 正则表达式替换

PHP preg_match_all 搜索和替换

lisp - CLOS 中的构造函数等价于什么?

arrays - 如何拥有两个相等但内部状态不同的数组

common-lisp - 更正正则表达式 "\[([a-zA-Z0-9_-]+)]"

python - 在 python 中使用正则表达式单词边界从字符串中提取单词

string - 在 Lisp 中使用 cond 时显示字符串

python - 使用 AutoCAD 中的 lisp 应用程序和 Python 3.5

lisp - 查找 Common Lisp 库