Clojure - Regular Expressions replace


Advertisements

replace

The replace function is used to replace a substring in a string with a new string value. The search for the substring is done with the use of a pattern.

Syntax

Following is the syntax.

(replace str pat replacestr)

Parameters − ‘pat’ is the regex pattern. ‘str’ is the string in which a text needs to be found based on the pattern. ‘replacestr’ is the string which needs to be replaced in the original string based on the pattern.

Return Value − The new string in which the replacement of the substring is done via the regex pattern.

Example

Following is an example of replace in Clojure.

(ns clojure.examples.example
   (:gen-class))

;; This program displays Hello World
(defn Example []
   (def pat (re-pattern "\\d+"))
   (def newstr (clojure.string/replace "abc123de" pat "789"))
   (println newstr))
(Example)

Output

The above program produces the following output.

abc789de
clojure_regular_expressions.htm
Advertisements