Clojure – Regular Expressions replace-first

Clojure Regular Expressions  replace-first

In this guide, we will discuss Clojure Regular Expressions replace-first.

replace-first

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

Syntax

Following is the syntax.

(replace-first 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, but only with the first occurrence.

Example

Following is an example of replace-first in Clojure.

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

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

The above example shows the difference between the replace and replace-first function.

Output

The above program produces the following output.

abc789de789
abc789de123

Next Topic : Click Here

This Post Has 2 Comments

Leave a Reply