What is the replace method in Clojure regular expression?

What is a regular expression?

Regular expressions in general are character sequence or code formats used in search patterns to streamline the search results of a string. A regular expression is used in the string search algorithm.

What is the replace method?

The replace method is used to replace the match pattern with a substring in a parent string.

Syntax

(replace string pattern replacestr)
Syntax of the replace method in Clojure

Parameters

The replace method receives one parameter following the syntax above.

  1. pattern: This is the pattern to be built.
  2. string: This is the parent string that contains the substring to be matched.
  3. replacestr: This is the string we replace in the parent string after matching the pattern.

Return value

The replace method returns a string with the replaced string.

Example

(ns clojure.examples.example
(:gen-class))
(defn func []
(def pattern (re-pattern "\\d+"))
(def newstring (clojure.string/replace "sam409uel" pattern "993"))
(println newstring))
(func)

Explanation

  • Line 4: We create a function func.
  • Line 5: We build our pattern using the re-pattern method (re-pattern "\\d+"), and we save it to a variable pattern.
  • Line 6: We carry out our string replacement using clojure.string/replace. We basically match all numbers in the string with sam409uel and replace them with 993.
  • Line 7: We print our variable newstring to the console.
  • Line 8: We call our function func.