Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

replace
clojure
regular expression
communitycreator

What is the replace method in Clojure regular expression?

Chinweuba Elijah Azubuike

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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)
An example of the repalce method in Clojure

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.

RELATED TAGS

replace
clojure
regular expression
communitycreator

CONTRIBUTOR

Chinweuba Elijah Azubuike

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring