Clojure Tutorial on Clojure Regular Expressions

a regular expression is a pattern that is used to find substrings in text. regular expressions are used in a variety of programming languages and used a lot in lisp type programming languages.

following is an example of a regular expression.

//d+

the above regular expression is used to find one more occurrence of a digit in a string. the // characters are used to ensure that characters ‘d’ and ‘+’ are used to represent a regular expression.

in general, regular expressions works with the following set of rules.

  • there are two special positional characters that are used to denote the beginning and end of a line: caret (∧) and dollar sign ($):

  • regular expressions can also include quantifiers. the plus sign (+) represents one or more times, applied to the preceding element of the expression. the asterisk (*) is used to represent zero or more occurrences. the question mark (?) denotes zero or once.

  • the metacharacter { and } is used to match a specific number of instances of the preceding character.

  • in a regular expression, the period symbol (.) can represent any character. this is described as the wildcard character.

  • a regular expression may include character classes. a set of characters can be given as a simple sequence of characters enclosed in the metacharacters [and] as in [aeiou]. for letter or number ranges, you can use a dash separator as in [a–z] or [a–ma–m]. the complement of a character class is denoted by a leading caret ithin the square brackets as in [∧a–z] and represents all characters other than those specified.

the following methods are available for regular expressions.

sr.no. methods & description
1 re-pattern

returns an instance of java.util.regex.pattern. this is then used in further methods for pattern matching.

2 refind

returns the next regex match, if any, of string to pattern, using java.util.regex.matcher.find()

3 replace

the replace function is used to replace a substring in a string with a new string value. the search for the substring is done with the use of a pattern.

4 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.