Site icon TestingDocs.com

Regular Expression in Java

Overview

A regular expression, regex is, in theoretical computer science and formal language theory, a sequence of characters that define a search pattern. Usually, this pattern is then used by string searching algorithms for “find” or “find and replace” operations on strings.

More at: https://en.wikipedia.org/wiki/Regular_expression

Sample Program

In Java language, you can import the regular expression capabilities by importing

java.util.regex package. The two main classes in the package are Pattern and Matcher.

Pattern

The Pattern is a compiled representation of a regular expression. A regular expression, specified as a string, must first be compiled into an instance of this class. The resulting pattern can then be used to create an Matcher object that can match arbitrary character sequences against the regular expression. All of the state involved in performing a match resides in the matcher, so many matchers can share the same pattern.

Matcher

An engine that performs match operations on a character sequence by interpreting a Pattern. A matcher is created from a pattern by invoking the pattern’s matcher method. Once created, a matcher can be used to perform three different kinds of match operations: find, matches, lookingAt, etc.

Let us run a simple java program to illustrate the use of regular expressions.

Code

public class RegExExample {

public static void main(String[] args) {
 Pattern pattern=Pattern.compile("T.*m");
 Matcher match = pattern.matcher("TestingDocs.com is a testing website");
 if(match.find())
 {
 System.out.println("String match from: "+ (match.start()+1)+"->"+
 (match.end()));
 }
 else
 {
 System.out.println("No Match Found in the given string.");
 }

}
}

 

Output of the program:

String match from: 1->15

 

 

The pattern ‘T.*m’ searches for the string starting with T followed by zero or more occurrences of any character and ending with m.

Note that : .* is a greedy match pattern.

Exit mobile version