Cl-ppcre: regex-replace and backslash instead

Perhaps these questions really got stuck, but I'm stuck. How can I put a backslash in the replacement cl-ppcre:regex-replace-all

?

For example, I just want to escape some characters like "" (), etc., so I will tackle substitution | replacement to make sure the match is ok:

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

      

Ok, let's slash:

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

      

No, we have replaced two slashes:

    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

      

Maybe so?

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

      

Of course, if I put a space between the forward slash, that's ok, but I don't need it

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

      

So how can I write to print foo \"bar\" \'baz\' \(test\)

? Thank you.

+3


source to share


2 answers


Six original forward slashes

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

      



When you write a string in your source code, each forward slash is used as an escape. You want the replacement text to be a sequence of characters \\1

. To encode the first forward slash in a replacement (since CL-PPCRE will handle forward slashes), CL-PPCRE must see a sequence of characters \\\1

. The first two slashes encode the forward slash and the third encodes the group number. To get this sequence of characters as a Lisp string, you must write "\\\\\\1"

.

+5


source


Late answer, but for others, note that in such cases you would avoid the lines:



(cl-ppcre:regex-replace-all '(:register (:char-class #\' #\( #\) #\"))
                            "foo \"bar\" 'baz' (test)"
                            '("\\" 0))

      

0


source







All Articles