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.
pattern: This is the pattern to be built.string: This is the parent string that contains the substring to be matched.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-patternmethod(re-pattern "\\d+"), and we save it to a variablepattern. - Line 6: We carry out our string replacement using
clojure.string/replace. We basically match all numbers in the string withsam409ueland replace them with993. - Line 7: We print our variable
newstringto the console. - Line 8: We call our function
func.