What is the re-find method in Clojure regular expression?

Overview

The regular expression is a character sequence or code format used in search patterns to streamline the search results, which are used in the string search algorithm.

The re-find method uses the java.util.regex.Matcher.find() to get the following regex (regular expression) of a string match pattern. It returns a string containing the matched pattern.

Syntax

(re-find pattern str)
Syntax of the re-find method in Clojure

Parameter

The re-find method receives two parameters following the syntax above.

  • pattern: This is the pattern to be built.
  • str: This is the string we are trying to match a search pattern with.

Return value

The re-find method returns a string containing the matched pattern.

Example

(ns clojure.examples.example
(:gen-class))
(defn func []
(def pattern (re-pattern "\\d+"))
(println (re-find pattern "sam123uel")))
(func)

Explanation

From the above example:

  • 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 named pattern.
  • Line 6: We print the return value of the re-find method, which is a string of numbers according to the pattern we built using the re-pattern method. We are just searching for numbers in a string.
  • Line 7: We call our function func.

Free Resources