What is regex in Java and How to use it.

Java Regex :

Java Regex and regular expression is an API which define pattern for searching or manipulating strings.

It provides following classes and interface for regular expression.

(i)   MatcherResult Interface
(ii)  Matcher class
(iii) Pattern class
(iv)  PatternSyntaxExeption class

Matcher class implements MatcherResult Interface which contains following methods.

(i) boolean matches() : test whether the regular expression matched the pattern.

(ii) boolean find() : find the next expression that matches the pattern.

(iii) boolean find(int start) : find the next expression that matches the pattern from the given start number.

Pattern Class : it is compiled version of a regular expression.

(i) static Pattern compile(String regex) : compile the given regex and return instance of Pattern class.

(ii) Matcher matcher(CharSequence input) : creates the matcher that matches the given input.

(iii) String Pattern() : return the regex pattern.

(iv) static boolean matches(String regex, CharSequence input) : it works as the combination of the compile and matcher methods.

Ex :

import java.util.regex.*;

public class RegexExample{

public static void main(String ar[]){

Pattern p = Pattern.compile(".s");
Matcher m = p.matcher("as");

boolean b1 = m.matches();

// OR

boolean b2 = Pattern.compile(".s").matcher("as").matches();

// OR

boolean b3 = Pattern.matches(".s","as");


}

Share this

Related Posts

Previous
Next Post »