Search code examples
clojure

Replace string with a regex containing a variable without macro


I need to delete some contents at the end of a string (eq_code) using Clojure. I want to implement a regex initialized by a variable (get-in vector [3 1]).

Maybe macro would have helped me.

Here is the code :

(reset! atom_code (clojure.string/replace eq_code #(str (get-in vector [3 1])) ""))

The error is :

IllegalArgumentException Invalid match arg: project.core$interpreted_lang_while$fn__4457@7ac4b7c5  clojure.string/replace (string.clj:102)

Is there a way to replace a substring without using macro ? For example using a function that return a regex.


Solution

  • https://clojuredocs.org/clojure.string/replace

    replace match parameter (second arg) can't be a function. The solution is to construct the pattern from your dynamic value:

    user> (def data [["a" "b"] ["c" "d"]])
    #'user/data
    
    user> (clojure.string/replace "mama" (re-pattern (get-in data [0 0])) "")
    "mm"
    

    and also: vector is the core function, so try not to shadow it by using it as a var name (though it's not actually what is wrong with your solution)