Clojure – Quick Guide

Clojure – Quick Guide ”; Previous Next Clojure – Overview Clojure is a high level, dynamic functional programming language. Clojure is designed based on the LISP programming language and has compilers which makes it run on both Java and .Net runtime environment. Before we talk about Clojure, let’s just have a quick description of LISP programming language. LISPs have a tiny language core, almost no syntax, and a powerful macro facility. With these features, you can bend LISP to meet your design, instead of the other way around. LISP has been there for a long time dating back to 1958. Common LISP reads in an expression, evaluates it, and then prints out the result. For example, if you want to compute the value of a simple mathematical expression of 4+6 then you type in. USER(1) (+ 4 6) Clojure has the following high-level key objectives as a programming language. It is based on the LISP programming language which makes its code statements smaller than traditional programming languages. It is a functional programming language. It focuses on immutability which is basically the concept that you should not make any changes to objects which are created in place. It can manage the state of an application for the programmer. It supports concurrency. It embraces existing programming languages. For example, Clojure can make use of the entire Java ecosystem for management of the running of the code via the JVM. The official website for Clojure is https://clojure.org/ Clojure – Environment There are a variety of ways to work with Clojure as a programming language. We will look at two ways to work with Clojure programming. Leiningen − Leiningen is an essential tool to create, build, and automate Clojure projects. Eclipse Plugin − There is a plugin called CounterClockwise, which is available for Eclipse for carrying out Clojure development in the Eclipse IDE. Leiningen Installation Ensure the following System requirements are met before proceeding with the installation. System Requirements JDK JDK 1.7 or above Memory 2 GB RAM (recommended) Step 1 − Download the binary installation. Go to the link http://leiningen-wininstallerto get the Windows Installer. Click on the option to start the download of the Groovy installer. Step 2 − Launch the Installer and click the Next button. Step 3 − Specify the location for the installation and click the Next button. Step 4 − The setup will detect the location of an existing Java installation. Click the Next button to proceed. Step 5 − Click the Install button to begin the installation. After the installation is complete, it will give you the option to open a Clojure REPL, which is an environment that can be used to create and test your Clojure programs. Eclipse Installation Ensure the following System requirements are met before proceeding with the installation. System Requirements JDK JDK 1.7 or above Eclipse Eclipse 4.5 (Mars) Step 1 − Open Eclipse and click the Menu item. Click Help → Eclipse Marketplace. Step 2 − Type in the keyword Clojure in the dialog box which appears and hit the ‘Go’ button. The option for counterclockwise will appear, click the Install button to begin the installation of this plugin. Step 3 − In the next dialog box, click the Confirm button to begin the installation. Step 4 − In the next dialog box, you will be requested to accept the license agreement. Accept the license agreement and click the Finish button to continue with the installation. The installation will begin, and once completed, it will prompt you to restart Eclipse. Once Eclipse is restarted, you will see the option in Eclipse to create a new Clojure project. Clojure – Basic Syntax In order to understand the basic syntax of Clojure, let’s first look at a simple Hello World program. Hello World as a Complete Program Write ‘Hello world’ in a complete Clojure program. Following is an example. Example Live Demo (ns clojure.examples.hello (:gen-class)) (defn hello-world [] (println “Hello World”)) (hello-world) The following things need to be noted about the above program. The program will be written in a file called main.clj. The extension ‘clj’ is the extension name for a clojure code file. In the above example, the name of the file is called main.clj. The ‘defn’ keyword is used to define a function. We will see functions in details in another chapter. But for now, know that we are creating a function called helloworld, which will have our main Clojure code. In our Clojure code, we are using the ‘println’ statement to print “Hello World” to the console output. We then call the hello-world function which in turn runs the ‘println’ statement. The above program produces the following output. Output Hello World General Form of a Statement The general form of any statement needs to be evaluated in braces as shown in the following example. (+ 1 2) In the above example, the entire expression is enclosed in braces. The output of the above statement is 3. The + operator acts like a function in Clojure, which is used for the addition of numerals. The values of 1 and 2 are known as parameters to the function. Let us consider another example. In this example, ‘str’ is the operator which is used to concatenate two strings. The strings “Hello” and “World” are used as parameters. (str “Hello” “World”) Example If we combine the above two statements and write a program, it will look like the following. Live Demo (ns clojure.examples.hello (:gen-class)) (defn Example [] (println (str “Hello World”)) (println (+ 1 2))) (Example) Output The above program produces the following output. Hello World 3 Namespaces A namespace is used to define a logical boundary between modules defined in Clojure. Current Namespace This defines the current namespace in which the current Clojure code resides in. Syntax *ns* Example In the REPL command window run the following command. *ns* Output When we run the above command, the output will defer depending on what is the current namespace. Following is an

Clojure – Databases

Clojure – Databases ”; Previous Next In order to use the database functionality, please ensure to first download the jdbc files from the following url − https://codeload.github.com/clojure/java.jdbc/zip/master You will find a zip file which has the necessary drivers for Clojure to have the ability to connect to databases. Once the zip file is extracted, ensure to add the unzipped location to your classpath. The main file for database connectivity is a file called jdbc.clj in the location clojure/java. The clojure jdbc connector supports a wide variety of databases, some of which are the following. H2Database Oracle Microsoft SQL Server MySQL PostgreSQL In our example, we are going to use MySQL DB as an example. The following operations are possible in Clojure with regards to Databases. Database Connection Before connecting to a MySQL database, make sure of the following − You have created a database TESTDB. You have created a table EMPLOYEE in TESTDB. This table has fields FIRST_NAME, LAST_NAME, AGE, SEX and INCOME. User ID “testuser” and password “test123” are set to access TESTDB. Ensure you have downloaded the ‘mysql jar file’ and added the file to your classpath. You have gone through MySQL tutorial to understand MySQL Basics. Syntax Following is the syntax to create a connection in Clojure. (def connection_name { :subprotocol “protocol_name” :subname “Location of mysql DB” :user “username” :password “password” }) Parameters − ‘connection_name’ is the name to be given to the connection. ‘subprotocol’ is the protocol to be used for the connection. By default we will be using the mysql protocol. ‘subname’ is the url to connect to the mysql db along with the database name. ‘user’ is the username used to connect to the database. ‘password’ is the password to be used to connect to the database. Return Value − This will provide a connection string, which can be used in subsequent mysql operations. The following example shows how to connect to the tables in the information schema and retrieve all the data in the table. Example (ns test.core (:require [clojure.java.jdbc :as sql])) (defn -main [] (def mysql-db { :subprotocol “mysql” :subname “//127.0.0.1:3306/information_schema” :user “root” :password “shakinstev”}) (println (sql/query mysql-db [“select table_name from tables”] :row-fn :table_name))) Querying Data Querying data on any database means to fetch some useful information from the database. Once a database connection is established, you are ready to make a query into this database. Following is the syntax by which data can be queried using Clojure. Syntax clojure.java.jdbc/query dbconn [“query”] :row-fn :sequence Parameters − ‘dbconn’ is the name of the connection used to connect to the database. ‘query’ is the query string used to fetch data from the database. ‘:sequence’ is by default all the rows of data fetched from the database and is returned as a sequence. The necessary operations on the sequence can then be done to see what data has been fetched. Return Value − This will return a sequence, which will have the rows of data from the query operation. The following example shows how to connect to the employee table and fetch the first_name column of the rows in the table. Example (ns test.core (:require [clojure.java.jdbc :as sql])) (defn -main [] (def mysql-db { :subprotocol “mysql” :subname “//127.0.0.1:3306/testdb” :user “root” :password “shakinstev”}) (println (sql/query mysql-db [“select first_name from employee”] :row-fn :first_name))) From the above code, we can see that The query of “select first_name from employee” is passed as the query string. The :first_name is the sequence, which is returned as a result of the fetch operation. If we assume that there is just one row in our database which contains a first_name value of John, following will be the output of the above program. (John) Inserting Data It is required when you want to create your records into a database table. Following is the syntax by which data can be inserted using Clojure. This is done by using the ‘insert!’ function. Syntax clojure.java.jdbc/insert! :table_name {:column_namen columnvalue} Parameters − ‘:table_name’ is the name of the table in which the insertion needs to be made. ‘{:column_namen columnvalue }’ is a map of all the column names and values, which need to be added as a row in the table. Return Value − This will return nil if the insertion is made successfully. The following example shows how to insert a record into the employee table in the testdb database. Example (ns test.core (:require [clojure.java.jdbc :as sql])) (defn -main [] (def mysql-db { :subprotocol “mysql” :subname “//127.0.0.1:3306/testdb” :user “root” :password “shakinstev”}) (sql/insert! mysql-db :employee {:first_name “John” :last_name “Mark” :sex “M” :age 30 :income 30})) If you now check your MySQL database and the employee table, you will see that the above row will be successfully inserted in the table. Deleting Data Rows can be deleted from a table by using the ‘delete!’ function. Following is the syntax on how this operation can be performed. Syntax clojure.java.jdbc/delete! :table_name [condition] Parameters − ‘:table_name’ is the name of the table in which the insertion needs to be made. ‘condition’ is the condition used to determine which row needs to be deleted from the table. Return Value − This will return the number of rows deleted. The following example shows how to delete a record from the employee table in the testdb database. The example deletes a row from the table based on the condition that the age is equal to 30. Example (ns test.core (:require [clojure.java.jdbc :as sql])) (defn -main [] (def mysql-db { :subprotocol “mysql” :subname “//127.0.0.1:3306/testdb” :user “root” :password “shakinstev”}) (println (sql/delete! mysql-db :employee [“age = ? ” 30]))) If you had a record which had a row with age equal to the value of 30, that row will be deleted. Updating Data Rows can be updated from a table by using the ‘update!’ function. Following is the syntax on how this operation can be performed. Syntax clojure.java.jdbc/update! :table_name {setcondition} [condition] Parameters − ‘:table_name’ is the name of the table in which the insertion needs to be made. ‘setcondition’ is the column which needs

Clojure – Libraries

Clojure – Libraries ”; Previous Next One thing which makes the Clojure library so powerful is the number of libraries available for the Clojure framework. We have already seen so many libraries used in our earlier examples for web testing, web development, developing swing-based applications, the jdbc library for connecting to MySQL databases. Following are just a couple of examples of few more libraries. data.xml This library allows Clojure to work with XML data. The library version to be used is org.clojure/data.xml “0.0.8”. The data.xml supports parsing and emitting XML. The parsing functions will read XML from a Reader or InputStream. Example Following is an example of the data processing from a string to XML. (ns clojure.examples.example (use ”clojure.data.xml) (:gen-class)) (defn Example [] (let [input-xml (java.io.StringReader. “<?xml version = “1.0” encoding = “UTF-8″?><example><clo><Tutorial>The Tutorial value</Tutorial></clo></example>”)] (parse input-xml))) #clojure.data.xml.Element{ :tag :example, :attrs {}, :content (#clojure.data.xml.Element { :tag :clo, :attrs {}, :content (#clojure.data.xml.Element { :tag :Tutorial, :attrs {},:content (“The Tutorial value”)})})} (Example) data.json This library allows Clojure to work with JSON data. The library version to be used is org.clojure/data.json “0.2.6”. Example Following is an example on the use of this library. Live Demo (ns clojure.examples.example (:require [clojure.data.json :as json]) (:gen-class)) (defn Example [] (println (json/write-str {:a 1 :b 2}))) (Example) Output The above program produces the following output. {“a”:1,”b”:2} data.csv This library allows Clojure to work with ‘csv’ data. The library version to be used is org.clojure/data.csv “0.1.3”. Example Following is an example on the use of this library. (ns clojure.examples.example (require ”[clojure.data.csv :as csv] ”[clojure.java.io :as io]) (:gen-class)) (defn Example [] (with-open [in-file (io/reader “in-file.csv”)] (doall (csv/read-csv in-file))) (with-open [out-file (io/writer “out-file.csv”)] (csv/write-csv out-file [[“:A” “a”] [“:B” “b”]]))) (Example) In the above code, the ‘csv’ function will first read a file called in-file.csv and put all the data in the variable in-file. Next, we are using the write-csv function to write all data to a file called out-file.csv. Print Page Previous Next Advertisements ”;

Clojure – Macros

Clojure – Macros ”; Previous Next In any language, Macros are used to generate inline code. Clojure is no exception and provides simple macro facilities for developers. Macros are used to write code-generation routines, which provide the developer a powerful way to tailor the language to the needs of the developer. Following are the methods available for Macros. defmacro This function is used to define your macro. The macro will have a macro name, a parameter list and the body of the macro. Syntax Following is the syntax. (defmacro name [params*] body) Parameters − ‘name’ is the name of the macro. ‘params’ are the parameters assigned to the macro. ‘body’ is the body of the macro. Return Value − None. Example An example on how this is used is shown in the following program. Live Demo (ns clojure.examples.example (:gen-class)) (defn Example [] (defmacro Simple [] (println “Hello”)) (macroexpand ”(Simple))) (Example) Output The above program produces the following output. Hello From the above program you can see that the macro ‘Simple’ is expanded inline to ‘println’ “Hello”. Macros are similar to functions, with the only difference that the arguments to a form are evaluated in the case of macros. macro-expand This is used to expand a macro and place the code inline in the program. Syntax Following is the syntax. (macroexpand macroname) Parameters − ‘macroname’ is the name of the macro which needs to be expanded. Return Value − The expanded macro. Example An example on how this is used is shown in the following program. Live Demo (ns clojure.examples.example (:gen-class)) (defn Example [] (defmacro Simple [] (println “Hello”)) (macroexpand ”(Simple))) (Example) Output The above program produces the following output. Hello Macro with Arguments Macros can also be used to take in arguments. The macro can take in any number of arguments. Following example showcases how arguments can be used. Example Live Demo (ns clojure.examples.example (:gen-class)) (defn Example [] (defmacro Simple [arg] (list 2 arg)) (println (macroexpand ”(Simple 2)))) (Example) The above example places an argument in the Simple macro and then uses the argument to add argument value to a list. Output The above program produces the following output. (2 2) Print Page Previous Next Advertisements ”;

Clojure – Date & Time

Clojure – Date and Time ”; Previous Next Since the Clojure framework is derived from Java classes, one can use the date-time classes available in Java in Clojure. The class date represents a specific instant in time, with millisecond precision. Following are the methods available for the date-time class. java.util.Date This is used to create the date object in Clojure. Syntax Following is the syntax. java.util.Date. Parameters − None. Return Value − Allocates a Date object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond. Example An example on how this is used is shown in the following program. Live Demo (ns example) (defn Example [] (def date (.toString (java.util.Date.))) (println date)) (Example) Output The above program produces the following output. This will depend on the current date and time on the system, on which the program is being run. Tue Mar 01 06:11:17 UTC 2016 java.text.SimpleDateFormat This is used to format the date output. Syntax Following is the syntax. (java.text.SimpleDateFormat. format dt) Parameters − ‘format’ is the format to be used when formatting the date. ‘dt’ is the date which needs to be formatted. Return Value − A formatted date output. Example An example on how this is used is shown in the following program. Live Demo (ns example) (defn Example [] (def date (.format (java.text.SimpleDateFormat. “MM/dd/yyyy”) (new java.util.Date))) (println date)) (Example) Output The above program produces the following output. This will depend on the current date and time on the system, on which the program is being run. 03/01/2016 getTime Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object. Syntax Following is the syntax. (.getTime) Parameters − None. Return Value − The number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this date. Example An example on how this is used is shown in the following program. Live Demo (ns example) (import java.util.Date) (defn Example [] (def date (.getTime (java.util.Date.))) (println date)) (Example) Output The above program produces the following output. This will depend on the current date and time on the system, on which the program is being run. 1456812778160 Print Page Previous Next Advertisements ”;

Clojure – Destructuring

Clojure – Destructuring ”; Previous Next Destructuring is a functionality within Clojure, which allows one to extract values from a data structure, such as a vector and bind them to symbols without having to explicitly traverse the datastructure. Let’s look at an example of what exactly Destructuring means and how does it happen. Example Live Demo (ns clojure.examples.example (:gen-class)) (defn Example [] (def my-vector [1 2 3 4]) (let [[a b c d] my-vector] (println a b c d))) (Example) The above program produces the following output. Output 1 2 3 4 In the above example, following things are to be noted − We are defining a vector of integers as 1 ,2, 3 and 4. We are then using the ‘let’ statement to assign 4 variables (a, b, c, and d) to the my-vector variable directly. If we run the ‘println’ statement on the four variables, we can see that they have already been assigned to the values in the vector respectively. So clojure has destructured the my-vector variable which has four values when it was assigned using the ‘let’ statement. The deconstructed four values were then assigned to the four parameters accordingly. If there are excess variables which don’t have a corresponding value to which they can be assigned to, then they will be assigned the value of nil. The following example makes this point clear. Example Live Demo (ns clojure.examples.hello (:gen-class)) (defn Example [] (def my-vector [1 2 3 4]) (let [[a b c d e] my-vector] (println a b c d e))) (Example) The above program produces the following output. You can see from the output that since the last variable ‘e’ does not have a corresponding value in the vector, it accounts to nil. Output 1 2 3 4 nil the-rest The ‘the-rest’ variable is used to store the remaining values, which cannot get assigned to any variable. An example on how this is used is shown in the following program. Example Live Demo (ns clojure.examples.example (:gen-class)) (defn Example [] (def my-vector [1 2 3 4]) (let [[a b & the-rest] my-vector] (println a b the-rest))) (Example) The above program produces the following output. From the output, you can clearly see that the values of 3 and 4 cannot be assigned to any variable so they are assigned to the ‘the-rest’ variable. Output 1 2 (3 4) Destructuring Maps Just like vectors, maps can also be destructured. Following is an example of how this can be accomplished. Example Live Demo (ns clojure.examples.example (:gen-class)) (defn Example [] (def my-map {“a” 1 “b” 2}) (let [{a “a” b “b”} my-map] (println a b))) (Example) The above program produces the following output. From the program you can clearly see that the map values of “a” and “b” are assigned to the variables of a and b. Output 1 2 Similarly in the case of vectors, if there is no corresponding value in the map when the destructuring happens, then the variable will be assigned a value of nil. Following is an example. Example Live Demo (ns clojure.examples.example (:gen-class)) (defn Example [] (def my-map {“a” 1 “b” 2}) (let [{a “a” b “b” c “c”} my-map] (println a b c))) (Example) The above program produces the following output. Output 1 2 nil Print Page Previous Next Advertisements ”;

Clojure – Metadata

Clojure – Metadata ”; Previous Next In Clojure, metadata is used to annotate the data in a collection or for the data stored in a symbol. This is normally used to annotate data about types to the underlying compiler, but can also be used for developers. Metadata is not considered as part of the value of the object. At the same time, metadata is immutable. The following operations are possible in Clojure with regards to metadata. Sr.No. Operations & Description 1 meta-with This function is used to define a metadata map for any object. 2 meta This function is used to see if any metadata is associated with an object. 3 vary-meta Returns an object of the same type and value as the original object, but with a combined metadata. Print Page Previous Next Advertisements ”;

Clojure – Concurrent Programming

Clojure – Concurrent Programming ”; Previous Next In Clojure programming most data types are immutable, thus when it comes to concurrent programming, the code using these data types are pretty safe when the code runs on multiple processors. But many a times, there is a requirement to share data, and when it comes to shared data across multiple processors, it becomes necessary to ensure that the state of the data is maintained in terms of integrity when working with multiple processors. This is known as concurrent programming and Clojure provides support for such programming. The software transactional memory system (STM), exposed through dosync, ref, set, alter, etc. supports sharing changing state between threads in a synchronous and coordinated manner. The agent system supports sharing changing state between threads in an asynchronous and independent manner. The atoms system supports sharing changing state between threads in a synchronous and independent manner. Whereas the dynamic var system, exposed through def, binding, etc. supports isolating changing state within threads. Other programming languages also follow the model for concurrent programming. They have a direct reference to the data which can be changed. If shared access is required, the object is locked, the value is changed, and the process continues for the next access to that value. In Clojure there are no locks, but Indirect references to immutable persistent data structures. There are three types of references in Clojure. Vars − Changes are isolated in threads. Refs − Changes are synchronized and coordinated between threads. Agents − Involves asynchronous independent changes between threads. The following operations are possible in Clojure with regards to concurrent programming. Transactions Concurrency in Clojure is based on transactions. References can only be changed within a transaction. Following rules are applied in transactions. All changes are atomic and isolated. Every change to a reference happens in a transaction. No transaction sees the effect made by another transaction. All transactions are placed inside of dosync block. We already seen what the dosync block does, let’s look at it again. dosync Runs the expression (in an implicit do) in a transaction that encompasses expression and any nested calls. Starts a transaction if none is already running on this thread. Any uncaught exception will abort the transaction and flow out of dosync. Following is the syntax. Syntax (dosync expression) Parameters − ‘expression’ is the set of expressions which will come in the dosync block. Return Value − None. Let’s look at an example wherein we try to change the value of a reference variable. Example Live Demo (ns clojure.examples.example (:gen-class)) (defn Example [] (def names (ref [])) (alter names conj “Mark”)) (Example) Output The above program when run gives the following error. Caused by: java.lang.IllegalStateException: No transaction running at clojure.lang.LockingTransaction.getEx(LockingTransaction.java:208) at clojure.lang.Ref.alter(Ref.java:173) at clojure.core$alter.doInvoke(core.clj:1866) at clojure.lang.RestFn.invoke(RestFn.java:443) at clojure.examples.example$Example.invoke(main.clj:5) at clojure.examples.example$eval8.invoke(main.clj:7) at clojure.lang.Compiler.eval(Compiler.java:5424) … 12 more From the error you can clearly see that you cannot change the value of a reference type without first initiating a transaction. In order for the above code to work, we have to place the alter command in a dosync block as done in the following program. Example Live Demo (ns clojure.examples.example (:gen-class)) (defn Example [] (def names (ref [])) (defn change [newname] (dosync (alter names conj newname))) (change “John”) (change “Mark”) (println @names)) (Example) The above program produces the following output. Output [John Mark] Let’s see another example of dosync. Example Live Demo (ns clojure.examples.example (:gen-class)) (defn Example [] (def var1 (ref 10)) (def var2 (ref 20)) (println @var1 @var2) (defn change-value [var1 var2 newvalue] (dosync (alter var1 – newvalue) (alter var2 + newvalue))) (change-value var1 var2 20) (println @var1 @var2)) (Example) In the above example, we have two values which are being changed in a dosync block. If the transaction is successful, both values will change else the whole transaction will fail. The above program produces the following output. Output 10 20 -10 40 Print Page Previous Next Advertisements ”;

Clojure – StructMaps

Clojure – StructMaps ”; Previous Next StructMaps are used for creating structures in Clojure. For example, if you wanted to create a structure which comprised of an Employee Name and Employeeid, you can do that with StructMaps. The following operations are possible in Clojure with regards to StructMaps. Sr.No. Operations & Description 1 defstruct This function is used for defining the structure which is required. 2 struct This function is used to define a structure object of the type, which is created by the defstruct operation. 3 struct-map This function is used to specifically assign values to key values by explicitly defining which values get assigned to which keys in the structure. 4 Accessing Individual Fields Individual fields of the structure can be accessed by accessing the keys along with the structure object. 5 Immutable Nature By default structures are also immutable, so if we try to change the value of a particular key, it will not change. 6 Adding a New Key to the Structure Since structures are immutable, the only way that another key can be added to the structure is via the creation of a new structure. An example on how this can be achieved is shown in the following program. Print Page Previous Next Advertisements ”;

Clojure – Regular Expressions

Clojure – Regular Expressions ”; Previous Next 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. Print Page Previous Next Advertisements ”;