Java Regex - Quick Guide


Advertisements


Java Regex - Overview

Java provides the java.util.regex package for pattern matching with regular expressions. Java regular expressions are very similar to the Perl programming language and very easy to learn.

A regular expression is a special sequence of characters that helps you match or find other strings or sets of strings, using a specialized syntax held in a pattern. They can be used to search, edit, or manipulate text and data.

The java.util.regex package primarily consists of the following three classes −

  • Pattern Class − A Pattern object is a compiled representation of a regular expression. The Pattern class provides no public constructors. To create a pattern, you must first invoke one of its public static compile() methods, which will then return a Pattern object. These methods accept a regular expression as the first argument.

  • Matcher Class − A Matcher object is the engine that interprets the pattern and performs match operations against an input string. Like the Pattern class, Matcher defines no public constructors. You obtain a Matcher object by invoking the matcher() method on a Pattern object.

  • PatternSyntaxException − A PatternSyntaxException object is an unchecked exception that indicates a syntax error in a regular expression pattern.

Java Regex - Capturing Groups

Capturing groups are a way to treat multiple characters as a single unit. They are created by placing the characters to be grouped inside a set of parentheses. For example, the regular expression (dog) creates a single group containing the letters "d", "o", and "g".

Capturing groups are numbered by counting their opening parentheses from the left to the right. In the expression ((A)(B(C))), for example, there are four such groups −

  • ((A)(B(C)))
  • (A)
  • (B(C))
  • (C)

To find out how many groups are present in the expression, call the groupCount method on a matcher object. The groupCount method returns an int showing the number of capturing groups present in the matcher's pattern.

There is also a special group, group 0, which always represents the entire expression. This group is not included in the total reported by groupCount.

Example

Following example illustrates how to find a digit string from the given alphanumeric string −

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexMatches {

   public static void main( String args[] ) {
      // String to be scanned to find the pattern.
      String line = "This order was placed for QT3000! OK?";
      String pattern = "(.*)(\\d+)(.*)";

      // Create a Pattern object
      Pattern r = Pattern.compile(pattern);

      // Now create matcher object.
      Matcher m = r.matcher(line);
      if (m.find( )) {
         System.out.println("Found value: " + m.group(0) );
         System.out.println("Found value: " + m.group(1) );
         System.out.println("Found value: " + m.group(2) );
      }else {
         System.out.println("NO MATCH");
      }
   }
}

This will produce the following result −

Output

Found value: This order was placed for QT3000! OK?
Found value: This order was placed for QT300
Found value: 0

Introduction

The java.util.regex.MatchResult interface represents the result of a match operation. This interface contains query methods used to determine the results of a match against a regular expression. The match boundaries, groups and group boundaries can be seen but not modified through a MatchResult.

Interface declaration

Following is the declaration for java.util.regex.MatchResult interface −

public interface MatchResult

Interface methods

S.N. Method & Description
1 int end()

Returns the offset after the last character matched.

2 int end(int group)

Returns the offset after the last character of the subsequence captured by the given group during this match.

3 String group()

Returns the input subsequence matched by the previous match.

4 String group(int group)

Returns the input subsequence captured by the given group during the previous match operation.

5 int groupCount()

Returns the number of capturing groups in this match result's pattern.

6 int start()

Returns the start index of the match.

7 int start(int group)

Returns the start index of the subsequence captured by the given group during this match.

java.util.regex.MatchResult.end() Method Example

Description

The java.time.MatchResult.end() method returns the offset after the last character matched.

Declaration

Following is the declaration for java.time.MatchResult.end() method.

int end()

Return Value

The offset after the last character matched.

Exceptions

  • IllegalStateException - If no match has yet been attempted, or if the previous match operation failed.

Example

The following example shows the usage of java.time.MatchResult.end() method.

package com.tutorialspoint;

import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatchResultDemo {
   private static final String REGEX = "(.*)(\\d+)(.*)";
   private static final String INPUT = "This is a sample Text, 1234, with numbers in between.";

   public static void main(String[] args) {
      // create a pattern
      Pattern pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      if(matcher.find()) {
         //get the MatchResult Object 
         MatchResult result = matcher.toMatchResult();

         //Prints the offset after the last character matched.
         System.out.println("First Capturing Group - Match String end(): "+result.end());         
      }
   }
}

Let us compile and run the above program, this will produce the following result −

First Capturing Group - Match String end(): 53

java.util.regex.MatchResult.end(int group) Method Example

Description

The java.time.MatchResult.end(int group) method returns the offset after the last character of the subsequence captured by the given group during this match.

Declaration

Following is the declaration for java.time.MatchResult.end(int group) method.

int end(int group)

Parameters

  • group - The index of a capturing group in this matcher's pattern.

Return Value

The offset after the last character matched.

Exceptions

  • IllegalStateException - If no match has yet been attempted, or if the previous match operation failed.

Example

The following example shows the usage of java.time.MatchResult.end(int group) method.

package com.tutorialspoint;

import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatchResultDemo {
   private static final String REGEX = "(.*)(\\d+)(.*)";
   private static final String INPUT = "This is a sample Text, 1234, with numbers in between.";

   public static void main(String[] args) {
      // create a pattern
      Pattern pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      if(matcher.find()) {
         //get the MatchResult Object 
         MatchResult result = matcher.toMatchResult();

         //Prints the offset after the last character of the subsequence captured by the given group during this match.
         System.out.println("Second Capturing Group - Match String - end(1): "+result.end(1));         
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Second Capturing Group - Match String - end(1): 26

java.util.regex.MatchResult.group() Method Example

Description

The java.time.MatchResult.group() method returns the input subsequence matched by the previous match.

Declaration

Following is the declaration for java.time.MatchResult.group() method.

String group()

Return Value

The (possibly empty) subsequence matched by the previous match, in string form.

Exceptions

  • IllegalStateException - If no match has yet been attempted, or if the previous match operation failed.

Example

The following example shows the usage of java.time.MatchResult.group() method.

package com.tutorialspoint;

import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatchResultDemo {
   private static final String REGEX = "(.*)(\\d+)(.*)";
   private static final String INPUT = "This is a sample Text, 1234, with numbers in between.";

   public static void main(String[] args) {
      // create a pattern
      Pattern pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      if(matcher.find()) {
         //get the MatchResult Object 
         MatchResult result = matcher.toMatchResult();

         //Prints the input subsequence matched by the previous match.
         System.out.println("First Capturing Group - Match String: "+result.group());     
      }
   }
}

Let us compile and run the above program, this will produce the following result −

First Capturing Group - Match String: This is a sample Text, 1234, with numbers in between.

java.util.regex.MatchResult.group(int group) Method Example

Description

The java.time.MatchResult.group(int group) method returns the input subsequence captured by the given group during the previous match operation.

Declaration

Following is the declaration for java.time.MatchResult.group(int group) method.

int group(int group)

Parameters

  • group - The index of a capturing group in this matcher's pattern.

Return Value

The (possibly empty) subsequence captured by the group during the previous match, or null if the group failed to match part of the input.

Exceptions

  • IllegalStateException - If no match has yet been attempted, or if the previous match operation failed.

  • IndexOutOfBoundsException - If there is no capturing group in the pattern with the given index.

Example

The following example shows the usage of java.time.MatchResult.group(int group) method.

package com.tutorialspoint;

import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatchResultDemo {
   private static final String REGEX = "(.*)(\\d+)(.*)";
   private static final String INPUT = "This is a sample Text, 1234, with numbers in between.";

   public static void main(String[] args) {
      // create a pattern
      Pattern pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      if(matcher.find()) {
         //get the MatchResult Object 
         MatchResult result = matcher.toMatchResult();

         //Prints the input subsequence captured by the given group during the previous match operation.
         System.out.println("Second Capturing Group - Match String: "+result.group(1));       
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Second Capturing Group - Match String: This is a sample Text, 123

java.util.regex.MatchResult.groupCount() Method Example

Description

The java.time.MatchResult.groupCount() method returns the number of capturing groups in this match result's pattern.

Declaration

Following is the declaration for java.time.MatchResult.groupCount() method.

int groupCount()

Return Value

The number of capturing groups in this matcher's pattern.

Example

The following example shows the usage of java.time.MatchResult.groupCount() method.

package com.tutorialspoint;

import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatchResultDemo {
   private static final String REGEX = "(.*)(\\d+)(.*)";
   private static final String INPUT = "This is a sample Text, 1234, with numbers in between.";

   public static void main(String[] args) {
      // create a pattern
      Pattern pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      if(matcher.find()) {
         //get the MatchResult Object 
         MatchResult result = matcher.toMatchResult();

         //Prints the number of capturing groups in this match result's pattern.
         System.out.println("Capturing Groups: "+result.groupCount());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

First Capturing Group - Match String: This is a sample Text, 1234, with numbers in between.

java.util.regex.MatchResult.start() Method Example

Description

The java.time.MatchResult.start() method returns the start index of the match.

Declaration

Following is the declaration for java.time.MatchResult.start() method.

int start()

Return Value

The index of the first character matched.

Exceptions

  • IllegalStateException - If no match has yet been attempted, or if the previous match operation failed.

Example

The following example shows the usage of java.time.MatchResult.start() method.

package com.tutorialspoint;

import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatchResultDemo {
   private static final String REGEX = "(.*)(\\d+)(.*)";
   private static final String INPUT = "This is a sample Text, 1234, with numbers in between.";

   public static void main(String[] args) {
      // create a pattern
      Pattern pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      if(matcher.find()) {
         //get the MatchResult Object 
         MatchResult result = matcher.toMatchResult();

         //Prints the start index of the match.
         System.out.println("First Capturing Group - Match String start(): "+result.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

First Capturing Group - Match String start(): 0

java.util.regex.MatchResult.start(int group) Method Example

Description

The java.time.MatchResult.start(int group) method returns the start index of the subsequence captured by the given group during this match.

Declaration

Following is the declaration for java.time.MatchResult.start(int group) method.

int start(int group)

Parameters

  • group - The index of a capturing group in this matcher's pattern.

Return Value

The index of the first character captured by the group, or -1 if the match was successful but the group itself did not match anything.

Exceptions

  • IllegalStateException - If no match has yet been attempted, or if the previous match operation failed.

  • IndexOutOfBoundsException - If there is no capturing group in the pattern with the given index.

Example

The following example shows the usage of java.time.MatchResult.start(int group) method.

package com.tutorialspoint;

import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatchResultDemo {
   private static final String REGEX = "(.*)(\\d+)(.*)";
   private static final String INPUT = "This is a sample Text, 1234, with numbers in between.";

   public static void main(String[] args) {
      // create a pattern
      Pattern pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      if(matcher.find()) {
         //get the MatchResult Object 
         MatchResult result = matcher.toMatchResult();

         //Prints the start index of the subsequence captured by the given group during this match.
         System.out.println("Second Capturing Group - Match String start(1): "+result.start(1));
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Second Capturing Group - Match String start(1): 0

java.util.regex - Pattern Class

Introduction

The java.util.regex.Pattern class represents a compiled representation of a regular expression.

Class declaration

Following is the declaration for java.util.regex.Pattern class −

public final class Pattern
   extends Object
      implements Serializable

Field

Following are the fields for java.util.regex.Duration class −

  • static int CANON_EQ - Enables canonical equivalence.

  • static int CASE_INSENSITIVE - Enables case-insensitive matching.

  • static int COMMENTS - Permits whitespace and comments in pattern.

  • static int DOTALL - Enables dotall mode.

  • static int LITERAL - Enables literal parsing of the pattern.

  • static int MULTILINE - Enables multiline mode.

  • static int UNICODE_CASE - Enables Unicode-aware case folding.

  • static int UNICODE_CHARACTER_CLASS - Enables the Unicode version of Predefined character classes and POSIX character classes.

  • static int UNIX_LINES - Enables Unix lines mode.

Class methods

S.N. Method & Description
1 static Pattern compile(String regex)

Compiles the given regular expression into a pattern.

2 static Pattern compile(String regex, int flags)

Compiles the given regular expression into a pattern with the given flags.

3 int flags()

Returns this pattern's match flags.

4 Matcher matcher(CharSequence input)

Creates a matcher that will match the given input against this pattern.

5 static boolean matches(String regex, CharSequence input)

Compiles the given regular expression and attempts to match the given input against it.

6 String pattern()

Returns the regular expression from which this pattern was compiled.

7 static String quote(String s)

Returns a literal pattern String for the specified String.

8 String[] split(CharSequence input)

Splits the given input sequence around matches of this pattern.

9 String[] split(CharSequence input, int limit)

Splits the given input sequence around matches of this pattern.

10 String toString()

Returns the string representation of this pattern.

Methods inherited

This class inherits methods from the following classes −

  • Java.lang.Object

java.util.regex.Pattern.compile(String regex) Method Example

Description

The java.util.regex.Pattern.compile(String regex) method compiles the given regular expression into a pattern.

Declaration

Following is the declaration for java.util.regex.Pattern.compile(String regex) method.

public static Pattern compile(String regex)

Parameters

  • regex - The expression to be compiled.

Exceptions

  • PatternSyntaxException - If the expression's syntax is invalid.

Example

The following example shows the usage of java.util.regex.Pattern.compile(String regex) method.

package com.tutorialspoint;

import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PatternDemo {
   private static final String REGEX = "(.*)(\\d+)(.*)";
   private static final String INPUT = "This is a sample Text, 1234, with numbers in between.";

   public static void main(String[] args) {
      // create a pattern
      Pattern pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      if(matcher.find()) {
         //get the MatchResult Object 
         MatchResult result = matcher.toMatchResult();

         //Prints the offset after the last character matched.
         System.out.println("First Capturing Group - Match String end(): "+result.end());         
      }
   }
}

Let us compile and run the above program, this will produce the following result −

First Capturing Group - Match String end(): 53

java.util.regex.Pattern.compile(String regex, int flags) Method Example

Description

The java.util.regex.Pattern.compile(String regex, int flags) method compiles the given regular expression into a pattern.

Declaration

Following is the declaration for java.util.regex.Pattern.compile(String regex, int flags) method.

public static Pattern compile(String regex, int flags)

Parameters

  • regex - The expression to be compiled.

  • flags - Match flags, a bit mask that may include CASE_INSENSITIVE, MULTILINE, DOTALL, UNICODE_CASE, CANON_EQ, UNIX_LINES, LITERAL, UNICODE_CHARACTER_CLASS and COMMENTS.

Exceptions

  • IllegalArgumentException - If bit values other than those corresponding to the defined match flags are set in flags.

  • PatternSyntaxException - If the expression's syntax is invalid.

Example

The following example shows the usage of java.util.regex.Pattern.compile(String regex, int flags) method.

package com.tutorialspoint;

import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PatternDemo {
   private static final String REGEX = "(.*)(\\d+)(.*)?# 3 capturing groups";
   private static final String INPUT = "This is a sample Text, 1234, with numbers in between.";

   public static void main(String[] args) {
      // create a pattern
      Pattern pattern = Pattern.compile(REGEX,Pattern.COMMENTS);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      if(matcher.find()) {
         //get the MatchResult Object 
         MatchResult result = matcher.toMatchResult();

         //Prints the offset after the last character matched.
         System.out.println("First Capturing Group - Match String end(): "+result.end());         
      }
   }
}

Let us compile and run the above program, this will produce the following result −

First Capturing Group - Match String end(): 53

java.util.regex.Pattern.flags() Method Example

Description

The java.util.regex.Pattern.flags() method returns this pattern's match flags.

Declaration

Following is the declaration for java.util.regex.Pattern.flags() method.

public int flags()

Return Value

The match flags specified when this pattern was compiled.

Example

The following example shows the usage of java.util.regex.Pattern.flags() method.

package com.tutorialspoint;

import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PatternDemo {
   private static final String REGEX = "(.*)(\\d+)(.*)?# 3 capturing groups";
   private static final String INPUT = "This is a sample Text, 1234, with numbers in between.";

   public static void main(String[] args) {
      // create a pattern
      Pattern pattern = Pattern.compile(REGEX,Pattern.COMMENTS);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      System.out.println(pattern.flags());
   }
}

Let us compile and run the above program, this will produce the following result −

4

java.util.regex.Pattern.matcher(CharSequence input) Method Example

Description

The java.util.regex.Pattern.matcher(CharSequence input) method creates a matcher that will match the given input against this pattern.

Declaration

Following is the declaration for java.util.regex.Pattern.matcher(CharSequence input) method.

public Matcher matcher(CharSequence input)

Parameters

  • input - The character sequence to be matched.

Returns

A new matcher for this pattern.

Example

The following example shows the usage of java.util.regex.Pattern.matcher(CharSequence input) method.

package com.tutorialspoint;

import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PatternDemo {
   private static final String REGEX = "(.*)(\\d+)(.*)";
   private static final String INPUT = "This is a sample Text, 1234, with numbers in between.";

   public static void main(String[] args) {
      // create a pattern
      Pattern pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      if(matcher.find()) {
         //get the MatchResult Object 
         MatchResult result = matcher.toMatchResult();

         //Prints the offset after the last character matched.
         System.out.println("First Capturing Group - Match String end(): "+result.end());         
      }
   }
}

Let us compile and run the above program, this will produce the following result −

First Capturing Group - Match String end(): 53

java.util.regex.Pattern.matches(String regex, CharSequence input) Method Example

Description

The java.util.regex.Pattern.matches(String regex, CharSequence input) method compiles the given regular expression and attempts to match the given input against it.

Declaration

Following is the declaration for java.util.regex.Pattern.matches(String regex, CharSequence input) method.

public static boolean matches(String regex, CharSequence input)

Parameters

  • regex - The expression to be compiled.

  • input - The character sequence to be matched.

Exceptions

  • PatternSyntaxException - If the expression's syntax is invalid.

Example

The following example shows the usage of java.util.regex.Pattern.matches(String regex, CharSequence input) method.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PatternDemo {

   private static final String REGEX = "foo*";
   private static final String INPUT = "fooooooooooooooooo";

   public static void main( String args[] ) {

      System.out.println("Current REGEX is: "+REGEX);
      System.out.println("Current INPUT is: "+INPUT);

      System.out.println("matches(): "+Pattern.matches(REGEX,INPUT));
   }
}

Let us compile and run the above program, this will produce the following result −

Current REGEX is: foo*
Current INPUT is: fooooooooooooooooo
matches(): true

java.util.regex.Pattern.pattern() Method Example

Description

The java.util.regex.Pattern.pattern() method returns the regular expression from which this pattern was compiled.

Declaration

Following is the declaration for java.util.regex.Pattern.pattern() method.

public String pattern()

Return Value

The source of this pattern.

Example

The following example shows the usage of java.util.regex.Pattern.pattern() method.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PatternDemo {
   private static final String REGEX = "(.*)(\\d+)(.*)?# 3 capturing groups";
   private static final String INPUT = "This is a sample Text, 1234, with numbers in between.";

   public static void main(String[] args) {
      // create a pattern
      Pattern pattern = Pattern.compile(REGEX,Pattern.COMMENTS);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      System.out.println(pattern.pattern());
   }
}

Let us compile and run the above program, this will produce the following result −

(.*)(\d+)(.*)?# 3 capturing groups

java.util.regex.Pattern.quote(String s) Method Example

Description

The java.util.regex.Pattern.quote(String s) method returns a literal pattern String for the specified String.

Declaration

Following is the declaration for java.util.regex.Pattern.quote(String s) method.

public static String quote(String s)

Parameters

  • s - The string to be literalized.

Returns

A literal string replacement.

Example

The following example shows the usage of java.util.regex.Pattern.quote(String s) method.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PatternDemo {
   private static String REGEX = "dog$";
   private static String INPUT = "The dog$ says meow " + "All dog$ say meow.";
   private static String REPLACE = "cat";

   public static void main(String[] args) {
      Pattern pattern = Pattern.compile(Pattern.quote(REGEX));
      
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 
      INPUT = matcher.replaceAll(REPLACE);
      System.out.println(INPUT);
   }
}

Let us compile and run the above program, this will produce the following result −

The cat says meow All cat say meow.

java.util.regex.Pattern.split(CharSequence input) Method Example

Description

The java.util.regex.Pattern.split(CharSequence input) method splits the given input sequence around matches of this pattern.

Declaration

Following is the declaration for java.util.regex.Pattern.split(CharSequence input) method.

public String[] split(CharSequence input)

Parameters

  • input - The character sequence to be split.

Returns

The array of strings computed by splitting the input around matches of this pattern.

Example

The following example shows the usage of java.util.regex.Pattern.split(CharSequence input) method.

package com.tutorialspoint;

import java.util.regex.Pattern;

public class PatternDemo {
   private static String REGEX = ":";
   private static String INPUT = "boo:and:foo";

   public static void main(String[] args) {
      Pattern pattern = Pattern.compile(REGEX);

      String[] result = pattern.split(INPUT);
      for(String data:result){
         System.out.println(data); 
      }
   }
}

Let us compile and run the above program, this will produce the following result −

boo
and
foo

java.util.regex.Pattern.split(CharSequence input, int limit) Method Example

Description

The java.util.regex.Pattern.split(CharSequence input, int limit) method splits the given input sequence around matches of this pattern.

Declaration

Following is the declaration for java.util.regex.Pattern.split(CharSequence input, int limit) method.

public String[] split(CharSequence input, int limit)

Parameters

  • input - The character sequence to be split.

  • limit - The result threshold.

Returns

The array of strings computed by splitting the input around matches of this pattern.

Example

The following example shows the usage of java.util.regex.Pattern.split(CharSequence input, int limit) method.

package com.tutorialspoint;

import java.util.regex.Pattern;

public class PatternDemo {
   private static String REGEX = ":";
   private static String INPUT = "boo:and:foo";

   public static void main(String[] args) {
      Pattern pattern = Pattern.compile(REGEX);

      String[] result = pattern.split(INPUT,2);
      for(String data:result){
         System.out.println(data); 
      }
   }
}

Let us compile and run the above program, this will produce the following result −

boo
and:foo

java.util.regex.Pattern.toString() Method Example

Description

The java.util.regex.Pattern.toString() method returns the string representation of this pattern. This is the regular expression from which this pattern was compiled.

Declaration

Following is the declaration for java.util.regex.Pattern.toString() method.

public String toString()

Return Value

he string representation of this pattern.

Example

The following example shows the usage of java.util.regex.Pattern.toString() method.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PatternDemo {
   private static final String REGEX = "(.*)(\\d+)(.*)?# 3 capturing groups";
   private static final String INPUT = "This is a sample Text, 1234, with numbers in between.";

   public static void main(String[] args) {
      // create a pattern
      Pattern pattern = Pattern.compile(REGEX,Pattern.COMMENTS);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      System.out.println(pattern.toString());
   }
}

Let us compile and run the above program, this will produce the following result −

(.*)(\d+)(.*)?# 3 capturing groups

java.util.regex - Matcher Class

Introduction

The java.util.regex.Matcher class acts as an engine that performs match operations on a character sequence by interpreting a Pattern.

Class declaration

Following is the declaration for java.util.regex.Matcher class −

public final class Matcher
   extends Object
      implements MatchResult

Class methods

S.N. Method & Description
1 Matcher appendReplacement(StringBuffer sb, String replacement)

Implements a non-terminal append-and-replace step.

2 StringBuffer appendTail(StringBuffer sb)

Implements a terminal append-and-replace step.

3 int end()

Returns the offset after the last character matched.

4 int end(int group)

Returns the offset after the last character of the subsequence captured by the given group during the previous match operation.

5 boolean find()

Attempts to find the next subsequence of the input sequence that matches the pattern.

6 boolean find(int start)

Resets this matcher and then attempts to find the next subsequence of the input sequence that matches the pattern, starting at the specified index.

7 String group()

Returns the input subsequence captured by the given group during the previous match operation.

8 String group(String name)

Returns the input subsequence captured by the given named-capturing group during the previous match operation.

9 int groupCount()

Returns the number of capturing groups in this matcher's pattern.

10 boolean hasAnchoringBounds()

Queries the anchoring of region bounds for this matcher.

11 boolean hasTransparentBounds()

Queries the transparency of region bounds for this matcher.

12 boolean hitEnd()

Returns true if the end of input was hit by the search engine in the last match operation performed by this matcher.

13 boolean lookingAt()

Attempts to match the input sequence, starting at the beginning of the region, against the pattern.

14 int regionEnd()

Attempts to match the entire region against the pattern.

15 Pattern pattern()

Returns the pattern that is interpreted by this matcher.

16 static String quoteReplacement(String s)

Returns a literal replacement String for the specified String.

17 Matcher region(int start, int end)

Sets the limits of this matcher's region.

18 int regionEnd()

Reports the end index (exclusive) of this matcher's region.

19 int regionStart()

Reports the start index of this matcher's region.

20 String replaceAll(String replacement)

Replaces every subsequence of the input sequence that matches the pattern with the given replacement string.

21 String replaceFirst(String replacement)

Replaces the first subsequence of the input sequence that matches the pattern with the given replacement string.

22 boolean requireEnd()

Returns true if more input could change a positive match into a negative one.

23 Matcher reset()

Resets this matcher.

24 Matcher reset(CharSequence input)

Resets this matcher with a new input sequence.

25 int start()

Returns the start index of the previous match.

26 int start(int group)

Returns the start index of the subsequence captured by the given group during the previous match operation.

27 MatchResult toMatchResult()

Returns the match state of this matcher as a MatchResult.

28 String toString()

Returns the string representation of this matcher.

29 Matcher useAnchoringBounds(boolean b)

Sets the anchoring of region bounds for this matcher.

30 Matcher usePattern(Pattern newPattern)

Changes the Pattern that this Matcher uses to find matches with.

31 Matcher useTransparentBounds(boolean b)

Sets the transparency of region bounds for this matcher.

Methods inherited

This class inherits methods from the following classes −

  • Java.lang.Object

java.util.regex.Matcher.appendReplacement(StringBuffer sb, String replacement) Method Example

Description

The java.time.Matcher.appendReplacement(StringBuffer sb, String replacement) method implements a non-terminal append-and-replace step.

Declaration

Following is the declaration for java.time.Matcher.appendReplacement(StringBuffer sb, String replacement) method.

public Matcher appendReplacement(StringBuffer sb, String replacement)

Parameters

  • sb - The target string buffer.

  • replacement - The replacement string.

Return Value

This matcher.

Exceptions

  • IllegalStateException - If no match has yet been attempted, or if the previous match operation failed.

  • IllegalArgumentException - If the replacement string refers to a named-capturing group that does not exist in the pattern.

  • IndexOutOfBoundsException - If the replacement string refers to a capturing group that does not exist in the pattern.

Example

The following example shows the usage of java.time.Matcher.appendReplacement(StringBuffer sb, String replacement) method.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatcherDemo {

   private static String REGEX = "a*b";
   private static String INPUT = "aabfooaabfooabfoob";
   private static String REPLACE = "-";
   public static void main(String[] args) {

      Pattern pattern = Pattern.compile(REGEX);
      
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT);
      StringBuffer buffer = new StringBuffer();
      while(matcher.find()) {
     matcher.appendReplacement(buffer, REPLACE);
      }
      matcher.appendTail(buffer);
      System.out.println(buffer.toString());
   }
}

Let us compile and run the above program, this will produce the following result −

-foo-foo-foo-

java.util.regex.Matcher.appendTail(StringBuffer sb) Method Example

Description

The java.time.Matcher.appendTail(StringBuffer sb) method implements a terminal append-and-replace step.

Declaration

Following is the declaration for java.time.Matcher.appendTail(StringBuffer sb) method.

public Matcher appendTail(StringBuffer sb)

Parameters

  • sb - The target string buffer.

Return Value

The target string buffer.

Example

The following example shows the usage of java.time.Matcher.appendTail(StringBuffer sb) method.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatcherDemo {

   private static String REGEX = "a*b";
   private static String INPUT = "aabfooaabfooabfoob";
   private static String REPLACE = "-";
   public static void main(String[] args) {

      Pattern pattern = Pattern.compile(REGEX);
      
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT);
      StringBuffer buffer = new StringBuffer();
      while(matcher.find()) {
     matcher.appendReplacement(buffer, REPLACE);
      }
      matcher.appendTail(buffer);
      System.out.println(buffer.toString());
   }
}

Let us compile and run the above program, this will produce the following result −

-foo-foo-foo-

java.util.regex.Matcher.end() Method Example

Description

The java.time.Matcher.end() method returns the offset after the last character matched.

Declaration

Following is the declaration for java.time.Matcher.end() method.

public int end()

Return Value

The offset after the last character matched.

Exceptions

  • IllegalStateException - If no match has yet been attempted, or if the previous match operation failed.

Example

The following example shows the usage of java.time.Matcher.end() method.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatcherDemo {

   private static String REGEX = "(a*b)(foo)";
   private static String INPUT = "aabfooaabfooabfoob";
   private static String REPLACE = "-";
   public static void main(String[] args) {

      Pattern pattern = Pattern.compile(REGEX);
      
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT);
      while(matcher.find()) {
     //Prints the offset after the last character matched.
          System.out.println("First Capturing Group, (a*b) Match String end(): "+matcher.end());    
      }      
   }
}

Let us compile and run the above program, this will produce the following result −

First Capturing Group, (a*b) Match String end(): 6
First Capturing Group, (a*b) Match String end(): 12
First Capturing Group, (a*b) Match String end(): 17

java.util.regex.Matcher.end(int group) Method Example

Description

The java.time.Matcher.end(int group) method returns the offset after the last character of the subsequence captured by the given group during the previous match operation.

Declaration

Following is the declaration for java.time.Matcher.end(int group) method.

public int end(int group)

Parameters

  • group - The index of a capturing group in this matcher's pattern.

Return Value

The offset after the last character captured by the group, or -1 if the match was successful but the group itself did not match anything.

Exceptions

  • IllegalStateException - If no match has yet been attempted, or if the previous match operation failed.

  • IndexOutOfBoundsException - If there is no capturing group in the pattern with the given index.

Example

The following example shows the usage of java.time.Matcher.end(int group) method.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatcherDemo {

   private static String REGEX = "(a*b)(foo)";
   private static String INPUT = "aabfooaabfooabfoob";
   private static String REPLACE = "-";
   public static void main(String[] args) {

      Pattern pattern = Pattern.compile(REGEX);
      
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT);
      while(matcher.find()) {
     //Prints the offset after the last character matched.
          System.out.println("Second Capturing Group, (foo) Match String end(): "+matcher.end(1));
      }      
   }
}

Let us compile and run the above program, this will produce the following result −

Second Capturing Group, (foo) Match String end(): 3
Second Capturing Group, (foo) Match String end(): 9
Second Capturing Group, (foo) Match String end(): 14

java.util.regex.Matcher.find() Method Example

Description

The java.time.Matcher.find() method attempts to find the next subsequence of the input sequence that matches the pattern.

Declaration

Following is the declaration for java.time.Matcher.find() method.

public boolean find()

Return Value

true if, and only if, a subsequence of the input sequence matches this matcher's pattern.

Example

The following example shows the usage of java.time.Matcher.find() method.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatcherDemo {

   private static String REGEX = "(a*b)(foo)";
   private static String INPUT = "aabfooaabfooabfoob";
   private static String REPLACE = "-";
   public static void main(String[] args) {

      Pattern pattern = Pattern.compile(REGEX);
      
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT);
      while(matcher.find()) {
     //Prints the offset after the last character matched.
          System.out.println("First Capturing Group, (a*b) Match String end(): "+matcher.end());    
          System.out.println("Second Capturing Group, (foo) Match String end(): "+matcher.end(1));  
      }
      
   }
}

Let us compile and run the above program, this will produce the following result −

First Capturing Group, (a*b) Match String end(): 6
Second Capturing Group, (foo) Match String end(): 3
First Capturing Group, (a*b) Match String end(): 12
Second Capturing Group, (foo) Match String end(): 9
First Capturing Group, (a*b) Match String end(): 17
Second Capturing Group, (foo) Match String end(): 14

java.util.regex.Matcher.find(int start) Method Example

Description

The java.time.Matcher.find(int start) method resets this matcher and then attempts to find the next subsequence of the input sequence that matches the pattern, starting at the specified index.

Declaration

Following is the declaration for java.time.Matcher.find(int start) method.

public boolean find(int start)

Parameters

  • start - start index in input string.

Return Value

true if, and only if, a subsequence of the input sequence starting at the given index matches this matcher's pattern

Exceptions

  • IndexOutOfBoundsException - If there is no capturing group in the pattern with the given index.

Example

The following example shows the usage of java.time.Matcher.find(int start) method.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatcherDemo {

   private static String REGEX = "(a*b)(foo)";
   private static String INPUT = "aabfooaabfooabfoob";
   private static String REPLACE = "-";
   public static void main(String[] args) {

      Pattern pattern = Pattern.compile(REGEX);
      
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT);
      if(matcher.find(6)) {
     //Prints the offset after the last character matched.
          System.out.println("First Capturing Group, (a*b) Match String end(): "+matcher.end());    
          System.out.println("Second Capturing Group, (foo) Match String end(): "+matcher.end(1));  
      }
      
   }
}

Let us compile and run the above program, this will produce the following result −

First Capturing Group, (a*b) Match String end(): 12
Second Capturing Group, (foo) Match String end(): 9

java.util.regex.Matcher.group() Method Example

Description

The java.time.Matcher.group() method attempts to find the next subsequence of the input sequence that matches the pattern.

Declaration

Following is the declaration for java.time.Matcher.group() method.

public String group()

Return Value

The (possibly empty) subsequence matched by the previous match, in string form.

  • IllegalStateException - If no match has yet been attempted, or if the previous match operation failed.

Example

The following example shows the usage of java.time.Matcher.group() method.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatcherDemo {

   private static String REGEX = "(a*b)(foo)";
   private static String INPUT = "aabfooaabfooabfoob";
   private static String REPLACE = "-";
   public static void main(String[] args) {

      Pattern pattern = Pattern.compile(REGEX);
      
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT);
      if(matcher.find()) {
     //Prints the offset after the last character matched.
          System.out.println("First Capturing Group: "+matcher.group());    
      }      
   }
}

Let us compile and run the above program, this will produce the following result −

First Capturing Group: aabfoo

java.util.regex.Matcher.group(int group) Method Example

Description

The java.time.Matcher.group(int group) method returns the input subsequence captured by the given group during the previous match operation.

Declaration

Following is the declaration for java.time.Matcher.group(int group) method.

public String group(int group)

Parameters

  • group - The index of a capturing group in this matcher's pattern.

Return Value

The (possibly empty) subsequence captured by the group during the previous match, or null if the group failed to match part of the input.

  • IllegalStateException - If no match has yet been attempted, or if the previous match operation failed.

  • IndexOutOfBoundsException - If there is no capturing group in the pattern with the given index.

Example

The following example shows the usage of java.time.Matcher.group(int group) method.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatcherDemo {

   private static String REGEX = "(a*b)(foo)";
   private static String INPUT = "aabfooaabfooabfoob";
   private static String REPLACE = "-";
   public static void main(String[] args) {

      Pattern pattern = Pattern.compile(REGEX);
      
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT);
      if(matcher.find()) {
     //Prints the offset after the last character matched.
          System.out.println("Second Capturing Group : "+matcher.group(1));
      }      
   }
}

Let us compile and run the above program, this will produce the following result −

Second Capturing Group : aab

java.util.regex.Matcher.groupCount() Method Example

Description

The java.time.Matcher.groupCount() method returns the number of capturing groups in this matcher's pattern.

Declaration

Following is the declaration for java.time.Matcher.groupCount() method.

public int groupCount()

Return Value

The number of capturing groups in this matcher's pattern.

Example

The following example shows the usage of java.time.Matcher.groupCount() method.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatcherDemo {

   private static String REGEX = "(a*b)(foo)";
   private static String INPUT = "aabfooaabfooabfoob";
   public static void main(String[] args) {

      Pattern pattern = Pattern.compile(REGEX);
      
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT);
      if(matcher.find()) {
     //Prints the number of capturing groups in this matcher's pattern.
          System.out.println("Group Count: "+matcher.groupCount());    
      }      
   }
}

Let us compile and run the above program, this will produce the following result −

Group Count: 2

java.util.regex.Matcher.hasAnchoringBounds() Method Example

Description

The java.time.Matcher.hasAnchoringBounds() method queries the anchoring of region bounds for this matcher.

Declaration

Following is the declaration for java.time.Matcher.hasAnchoringBounds() method.

public boolean hasAnchoringBounds()

Return Value

true if this matcher is using anchoring bounds, false otherwise.

Example

The following example shows the usage of java.time.Matcher.hasAnchoringBounds() method.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatcherDemo {

   private static String REGEX = "(a*b)(foo)";
   private static String INPUT = "aabfooaabfooabfoob";
   public static void main(String[] args) {

      Pattern pattern = Pattern.compile(REGEX);
      
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT);
      
      System.out.println("hasAnchoringBounds(): " + matcher.hasAnchoringBounds());
      
   }
}

Let us compile and run the above program, this will produce the following result −

hasAnchoringBounds(): true

java.util.regex.Matcher.hasTransparentBounds() Method Example

Description

The java.time.Matcher.hasTransparentBounds() method queries the transparency of region bounds for this matcher.

Declaration

Following is the declaration for java.time.Matcher.hasTransparentBounds() method.

public boolean hasTransparentBounds()

Return Value

true if this matcher is using transparent bounds, false otherwise.

Example

The following example shows the usage of java.time.Matcher.hasTransparentBounds() method.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatcherDemo {

   private static String REGEX = "(a*b)(foo)";
   private static String INPUT = "aabfooaabfooabfoob";
   public static void main(String[] args) {

      Pattern pattern = Pattern.compile(REGEX);
      
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT);
      
      System.out.println("hasTransparentBounds(): " + matcher.hasTransparentBounds());
      
   }
}

Let us compile and run the above program, this will produce the following result −

hasTransparentBounds(): false

java.util.regex.Matcher.hitEnd() Method Example

Description

The java.time.Matcher.hitEnd() method returns true if the end of input was hit by the search engine in the last match operation performed by this matcher.

Declaration

Following is the declaration for java.time.Matcher.hitEnd() method.

public boolean hitEnd()

Return Value

true if the end of input was hit in the last match; false otherwise

Example

The following example shows the usage of java.time.Matcher.hitEnd() method.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatcherDemo {

   private static String REGEX = "(a*b)(foo)";
   private static String INPUT = "aabfooaabfooabfoob";
   private static String REPLACE = "-";
   public static void main(String[] args) {

      Pattern pattern = Pattern.compile(REGEX);
      
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT);
      while(matcher.find()) {
     //Prints the offset after the last character matched.
          System.out.println("First Capturing Group, (a*b) Match String end(): "+matcher.end());    
      }
      System.out.println("hitEnd(): "+matcher.hitEnd());    
   }
}

Let us compile and run the above program, this will produce the following result −

First Capturing Group, (a*b) Match String end(): 6
First Capturing Group, (a*b) Match String end(): 12
First Capturing Group, (a*b) Match String end(): 17
hitEnd(): true

java.util.regex.Matcher.lookingAt() Method Example

Description

The java.time.Matcher.lookingAt() method attempts to match the input sequence, starting at the beginning of the region, against the pattern.

Declaration

Following is the declaration for java.time.Matcher.lookingAt() method.

public boolean lookingAt()

Return Value

true if, and only if, a prefix of the input sequence matches this matcher's pattern.

Example

The following example shows the usage of java.time.Matcher.lookingAt() method.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatcherDemo {

   private static final String REGEX = "foo";
   private static final String INPUT = "fooooooooooooooooo";
   private static Pattern pattern;
   private static Matcher matcher;

   public static void main( String args[] ) {
      pattern = Pattern.compile(REGEX);
      matcher = pattern.matcher(INPUT);

      System.out.println("Current REGEX is: "+REGEX);
      System.out.println("Current INPUT is: "+INPUT);

      System.out.println("lookingAt(): "+matcher.lookingAt());
      System.out.println("matches(): "+matcher.matches());
   }
}

Let us compile and run the above program, this will produce the following result −

Current REGEX is: foo
Current INPUT is: fooooooooooooooooo
lookingAt(): true
matches(): false

java.util.regex.Matcher.matches() Method Example

Description

The java.time.Matcher.matches() method attempts to match the entire region against the pattern.

Declaration

Following is the declaration for java.time.Matcher.matches() method.

public boolean matches()

Return Value

true if, and only if, the entire region sequence matches this matcher's pattern.

Example

The following example shows the usage of java.time.Matcher.matches() method.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatcherDemo {

   private static final String REGEX = "foo";
   private static final String INPUT = "fooooooooooooooooo";
   private static Pattern pattern;
   private static Matcher matcher;

   public static void main( String args[] ) {
      pattern = Pattern.compile(REGEX);
      matcher = pattern.matcher(INPUT);

      System.out.println("Current REGEX is: "+REGEX);
      System.out.println("Current INPUT is: "+INPUT);

      System.out.println("lookingAt(): "+matcher.lookingAt());
      System.out.println("matches(): "+matcher.matches());
   }
}

Let us compile and run the above program, this will produce the following result −

Current REGEX is: foo
Current INPUT is: fooooooooooooooooo
lookingAt(): true
matches(): false

java.util.regex.Matcher.pattern() Method Example

Description

The java.time.Matcher.pattern() method returns the pattern that is interpreted by this matcher.

Declaration

Following is the declaration for java.time.Matcher.pattern() method.

public Pattern pattern()

Return Value

The pattern for which this matcher was created.

Example

The following example shows the usage of java.time.Matcher.pattern() method.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatcherDemo {

   private static final String REGEX = "foo";
   private static final String INPUT = "fooooooooooooooooo";
   private static Pattern pattern;
   private static Matcher matcher;

   public static void main( String args[] ) {
      pattern = Pattern.compile(REGEX);
      matcher = pattern.matcher(INPUT);

      System.out.println("Current REGEX is: "+REGEX);
      System.out.println("Current INPUT is: "+INPUT);

      System.out.println("pattern(): "+matcher.pattern());
      System.out.println("matches(): "+matcher.matches());
   }
}

Let us compile and run the above program, this will produce the following result −

Current REGEX is: foo
Current INPUT is: fooooooooooooooooo
pattern(): foo
matches(): false

java.util.regex.Matcher.quoteReplacement(String s) Method Example

Description

The java.time.Matcher.quoteReplacement(String s) method returns a literal replacement String for the specified String.

Declaration

Following is the declaration for java.time.Matcher.quoteReplacement(String s) method.

public static String quoteReplacement(String s)

Parameters

  • s - The string to be literalized.

Return Value

A literal string replacement.

Example

The following example shows the usage of java.time.Matcher.quoteReplacement(String s) method.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatcherDemo {
   private static String REGEX = "dog";
   private static String INPUT = "The dog says meow " + "All dogs say meow.";
   private static String REPLACE = "cat$";

   public static void main(String[] args) {
      Pattern pattern = Pattern.compile(REGEX);
      
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 
      try{
     //Below line will throw exception
     INPUT = matcher.replaceAll(REPLACE);
      }catch(Exception e){
     System.out.println("Exception: "+ e.getMessage());
      }
      INPUT = matcher.replaceAll(matcher.quoteReplacement(REPLACE));
      System.out.println(INPUT);
   }
}

Let us compile and run the above program, this will produce the following result −

Exception: Illegal group reference: group index is missing
The cat$ says meow All cat$s say meow.

java.util.regex.Matcher.region(int start, int end) Method Example

Description

The java.util.regex.Matcher.region(int start, int end) method sets the limits of this matcher's region. The region is the part of the input sequence that will be searched to find a match. Invoking this method resets the matcher, and then sets the region to start at the index specified by the start parameter and end at the index specified by the end parameter.

Declaration

Following is the declaration for java.util.regex.Matcher.region(int start, int end) method.

public Matcher region(int start, int end)

Parameters

  • start - The index to start searching at (inclusive).

  • end - The index to end searching at (exclusive).

Return Value

this matcher.

Example

The following example shows the usage of java.util.regex.Matcher.region(int start, int end) method.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatcherDemo {

   private static String REGEX = "(a*b)(foo)";
   private static String INPUT = "aabfooaabfooabfoob";
   private static String REPLACE = "-";
   public static void main(String[] args) {

      Pattern pattern = Pattern.compile(REGEX);
      
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT);
      matcher = matcher.region(0, 10);
      while(matcher.find()) {
     //Prints the offset after the last character matched.
          System.out.println("First Capturing Group, (a*b) Match String end(): "+matcher.end());    
      }     
   }
}

Let us compile and run the above program, this will produce the following result −

First Capturing Group, (a*b) Match String end(): 6

java.util.regex.Matcher.regionEnd() Method Example

Description

The java.util.regex.Matcher.regionEnd() method reports the end index (exclusive) of this matcher's region. The searches this matcher conducts are limited to finding matches within regionStart (inclusive) and regionEnd (exclusive).

Declaration

Following is the declaration for java.util.regex.Matcher.regionEnd() method.

public int regionEnd()

Return Value

the ending point of this matcher's region.

Example

The following example shows the usage of java.util.regex.Matcher.regionEnd() method.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatcherDemo {

   private static String REGEX = "(a*b)(foo)";
   private static String INPUT = "aabfooaabfooabfoob";
   private static String REPLACE = "-";
   public static void main(String[] args) {

      Pattern pattern = Pattern.compile(REGEX);
      
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT);
      matcher = matcher.region(0, 10);
      while(matcher.find()) {
     //Prints the offset after the last character matched.
          System.out.println("First Capturing Group, (a*b) Match String end(): "+matcher.end());    
      }     
      System.out.println("regionEnd(): "+matcher.regionEnd());    
   }
}

Let us compile and run the above program, this will produce the following result −

First Capturing Group, (a*b) Match String end(): 6
regionEnd(): 10

java.util.regex.Matcher.regionStart() Method Example

Description

The java.util.regex.Matcher.regionStart() method reports the start index of this matcher's region. The searches this matcher conducts are limited to finding matches within regionStart (inclusive) and regionEnd (exclusive).

Declaration

Following is the declaration for java.util.regex.Matcher.regionStart() method.

public int regionStart()

Return Value

the ending point of this matcher's region.

Example

The following example shows the usage of java.util.regex.Matcher.regionStart() method.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatcherDemo {

   private static String REGEX = "(a*b)(foo)";
   private static String INPUT = "aabfooaabfooabfoob";
   private static String REPLACE = "-";
   public static void main(String[] args) {

      Pattern pattern = Pattern.compile(REGEX);
      
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT);
      matcher = matcher.region(0, 10);
      while(matcher.find()) {
     //Prints the offset after the last character matched.
          System.out.println("First Capturing Group, (a*b) Match String end(): "+matcher.end());    
      }     
      System.out.println("regionStart(): "+matcher.regionStart());    
   }
}

Let us compile and run the above program, this will produce the following result −

First Capturing Group, (a*b) Match String end(): 6
regionStart(): 0

java.util.regex.Matcher.replaceAll(String replacement) Method Example

Description

The java.util.regex.Matcher.replaceAll(String replacement) method replaces every subsequence of the input sequence that matches the pattern with the given replacement string.

Declaration

Following is the declaration for java.util.regex.Matcher.replaceAll(String replacement) method.

public String replaceAll(String replacement)

Parameters

  • replacement - The replacement string.

Return Value

The string constructed by replacing each matching subsequence by the replacement string, substituting captured subsequences as needed.

Example

The following example shows the usage of java.util.regex.Matcher.replaceAll(String replacement) method.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatcherDemo {
   private static String REGEX = "dog";
   private static String INPUT = "The dog says meow " + "All dogs say meow.";
   private static String REPLACE = "cat";

   public static void main(String[] args) {
      Pattern pattern = Pattern.compile(REGEX);
      
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 
      INPUT = matcher.replaceAll(REPLACE);
      System.out.println(INPUT);
   }
}

Let us compile and run the above program, this will produce the following result −

The cat says meow All cats say meow.

java.util.regex.Matcher.replaceFirst(String replacement) Method Example

Description

The java.util.regex.Matcher.replaceFirst(String replacement) method replaces the first subsequence of the input sequence that matches the pattern with the given replacement string.

Declaration

Following is the declaration for java.util.regex.Matcher.replaceFirst(String replacement) method.

public String replaceFirst(String replacement)

Parameters

  • replacement - The replacement string.

Return Value

The string constructed by replacing the first matching subsequence by the replacement string, substituting captured subsequences as needed.

Example

The following example shows the usage of java.util.regex.Matcher.replaceFirst(String replacement) method.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatcherDemo {
   private static String REGEX = "dog";
   private static String INPUT = "The dog says meow " + "All dogs say meow.";
   private static String REPLACE = "cat";

   public static void main(String[] args) {
      Pattern pattern = Pattern.compile(REGEX);
      
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 
      INPUT = matcher.replaceFirst(REPLACE);
      System.out.println(INPUT);
   }
}

Let us compile and run the above program, this will produce the following result −

The cat says meow All dogs say meow.

java.util.regex.Matcher.requireEnd() Method Example

Description

The java.util.regex.Matcher.requireEnd() method returns true if more input could change a positive match into a negative one.

Declaration

Following is the declaration for java.util.regex.Matcher.requireEnd() method.

public boolean requireEnd()

Return Value

true if and only if more input could change a positive match into a negative one.

Example

The following example shows the usage of java.util.regex.Matcher.requireEnd() method.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatcherDemo {

   private static String REGEX = "(a*b)(foo)";
   private static String INPUT = "aabfooaabfooabfoob";
   private static String REPLACE = "-";
   public static void main(String[] args) {

      Pattern pattern = Pattern.compile(REGEX);
      
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT);
      while(matcher.find()) {
     //Prints the offset after the last character matched.
          System.out.println("First Capturing Group, (a*b) Match String end(): "+matcher.end());   
          System.out.println("requireEnd(): "+matcher.requireEnd());    
      }     
   }
}

Let us compile and run the above program, this will produce the following result −

First Capturing Group, (a*b) Match String end(): 6
requireEnd(): false
First Capturing Group, (a*b) Match String end(): 12
requireEnd(): false
First Capturing Group, (a*b) Match String end(): 17
requireEnd(): false

java.util.regex.Matcher.reset() Method Example

Description

The java.util.regex.Matcher.reset() method resets this matcher.

Declaration

Following is the declaration for java.util.regex.Matcher.reset() method.

public Matcher reset()

Return Value

This matcher.

Example

The following example shows the usage of java.util.regex.Matcher.reset() method.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatcherDemo {

   private static String REGEX = "(a*b)(foo)";
   private static String INPUT = "aabfooaabfooabfoob";
   private static String REPLACE = "-";
   public static void main(String[] args) {

      Pattern pattern = Pattern.compile(REGEX);
      
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT);   
      matcher.region(10, 15);
      System.out.println("Before reset, regionStart(): " + matcher.regionStart());
      System.out.println("Before reset, regionEnd(): " + matcher.regionEnd());
      matcher.reset();
      System.out.println("After reset, regionStart(): " + matcher.regionStart());
      System.out.println("After reset, regionEnd(): " + matcher.regionEnd());
      
   }
}

Let us compile and run the above program, this will produce the following result −

Before reset, regionStart(): 10
Before reset, regionEnd(): 15
After reset, regionStart(): 0
After reset, regionEnd(): 18

java.util.regex.Matcher.reset(CharSequence input) Method Example

Description

The java.util.regex.Matcher.reset(CharSequence input) method Resets this matcher with a new input sequence.

Declaration

Following is the declaration for java.util.regex.Matcher.reset(CharSequence input) method.

public Matcher reset(CharSequence input)

Parameters

  • input - The new input character sequence.

Return Value

This matcher.

Example

The following example shows the usage of java.util.regex.Matcher.reset(CharSequence input) method.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatcherDemo {

   private static String REGEX = "(a*b)(foo)";
   private static String INPUT = "aabfooaabfooabfoob";
   private static String INPUT1 = "fooabfoob";
   private static String REPLACE = "-";
   public static void main(String[] args) {

      Pattern pattern = Pattern.compile(REGEX);
      
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT);   
      
      while(matcher.find()) {
      //Prints the offset after the last character matched.
          System.out.println("First Capturing Group, (a*b) Match String end(): "+matcher.end());   
      }     
      
      matcher.reset(INPUT1);
      System.out.println("RESET");
      while(matcher.find()) {
      //Prints the offset after the last character matched.
          System.out.println("First Capturing Group, (a*b) Match String end(): "+matcher.end());   
      }     
      
   }
}

Let us compile and run the above program, this will produce the following result −

First Capturing Group, (a*b) Match String end(): 6
First Capturing Group, (a*b) Match String end(): 12
First Capturing Group, (a*b) Match String end(): 17
RESET
First Capturing Group, (a*b) Match String end(): 8

java.util.regex.Matcher.start() Method Example

Description

The java.util.regex.Matcher.start() method returns the start index of the previous match.

Declaration

Following is the declaration for java.util.regex.Matcher.start() method.

public int start()

Return Value

The index of the first character matched.

Exceptions

  • IllegalStateException - If no match has yet been attempted, or if the previous match operation failed.

Example

The following example shows the usage of java.util.regex.Matcher.start() method.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatcherDemo {

   private static String REGEX = "(a*b)(foo)";
   private static String INPUT = "aabfooaabfooabfoob";
   private static String REPLACE = "-";
   public static void main(String[] args) {

      Pattern pattern = Pattern.compile(REGEX);
      
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT);
      while(matcher.find()) {
     //Prints the start index of the previous match.
          System.out.println("First Capturing Group, (a*b) Match String start(): "+matcher.start());    
      }      
   }
}

Let us compile and run the above program, this will produce the following result −

First Capturing Group, (a*b) Match String start(): 0
First Capturing Group, (a*b) Match String start(): 6
First Capturing Group, (a*b) Match String start(): 12

java.util.regex.Matcher.start(int group) Method Example

Description

The java.util.regex.Matcher.start(int group) method returns the start index of the subsequence captured by the given group during the previous match operation.

Declaration

Following is the declaration for java.util.regex.Matcher.start(int group) method.

public int start(int group)

Parameters

  • group - The index of a capturing group in this matcher's pattern.

Return Value

The index of the first character captured by the group, or -1 if the match was successful but the group itself did not match anything.

Exceptions

  • IllegalStateException - If no match has yet been attempted, or if the previous match operation failed.

  • IndexOutOfBoundsException - If there is no capturing group in the pattern with the given index.

Example

The following example shows the usage of java.util.regex.Matcher.start(int group) method.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatcherDemo {

   private static String REGEX = "(a*b)(foo)";
   private static String INPUT = "aabfooaabfooabfoob";
   private static String REPLACE = "-";
   public static void main(String[] args) {

      Pattern pattern = Pattern.compile(REGEX);
      
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT);
      while(matcher.find()) {
     //Prints the start index of the subsequence captured by the given group.
          System.out.println("Second Capturing Group, (foo) Match String start(): "+matcher.start(1));
      }      
   }
}

Let us compile and run the above program, this will produce the following result −

Second Capturing Group, (foo) Match String start(): 0
Second Capturing Group, (foo) Match String start(): 6
Second Capturing Group, (foo) Match String start(): 12

java.util.regex.Matcher.toMatchResult() Method Example

Description

The java.util.regex.Matcher.toMatchResult() method returns the match state of this matcher as a MatchResult. The result is unaffected by subsequent operations performed upon this matcher.

Declaration

Following is the declaration for java.util.regex.Matcher.toMatchResult() method.

public MatchResult toMatchResult()

Return Value

a MatchResult with the state of this matcher.

Example

The following example shows the usage of java.util.regex.Matcher.toMatchResult() method.

package com.tutorialspoint;

import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatcherDemo {
   private static final String REGEX = "(.*)(\\d+)(.*)";
   private static final String INPUT = "This is a sample Text, 1234, with numbers in between.";

   public static void main(String[] args) {
      // create a pattern
      Pattern pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      if(matcher.find()) {
         //get the MatchResult Object 
         MatchResult result = matcher.toMatchResult();

         //Prints the offset after the last character of the subsequence captured by the given group during this match.
         System.out.println("Second Capturing Group - Match String - end(1): "+result.end(1));         
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Second Capturing Group - Match String - end(1): 26

java.util.regex.Matcher.toString() Method Example

Description

The java.util.regex.Matcher.toString() method returns the string representation of this matcher. The string representation of a Matcher contains information that may be useful for debugging. The exact format is unspecified.

Declaration

Following is the declaration for java.util.regex.Matcher.toString() method.

public MatchResult toString()

Return Value

The string representation of this matcher.

Example

The following example shows the usage of java.util.regex.Matcher.toString() method.

package com.tutorialspoint;

import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatcherDemo {
   private static final String REGEX = "(.*)(\\d+)(.*)";
   private static final String INPUT = "This is a sample Text, 1234, with numbers in between.";

   public static void main(String[] args) {
      // create a pattern
      Pattern pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 
      System.out.println(matcher.toString());
   }
}

Let us compile and run the above program, this will produce the following result −

java.util.regex.Matcher[pattern=(.*)(\d+)(.*) region=0,53 lastmatch=]

java.util.regex.Matcher.useAnchoringBounds(boolean b) Method Example

Description

The java.util.regex.Matcher.useAnchoringBounds(boolean b) method sets the anchoring of region bounds for this matcher.

Declaration

Following is the declaration for java.util.regex.Matcher.useAnchoringBounds(boolean b) method.

public Matcher useAnchoringBounds(boolean b)

Parameters

  • b - a boolean indicating whether or not to use anchoring bounds.

Return Value

this matcher.

Example

The following example shows the usage of java.util.regex.Matcher.useAnchoringBounds(boolean b) method.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatcherDemo {
   private static final String REGEX = "(.*)(\\d+)(.*)";
   private static final String INPUT = "This is a sample Text, 1234, with numbers in between.";

   public static void main(String[] args) {
      // create a pattern
      Pattern pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 
      matcher.useAnchoringBounds(true);
      System.out.println(matcher.hasAnchoringBounds());
   }
}

Let us compile and run the above program, this will produce the following result −

true

java.util.regex.Matcher.usePattern(Pattern newPattern) Method Example

Description

The java.util.regex.Matcher.usePattern(Pattern newPattern) method changes the Pattern that this Matcher uses to find matches with.

Declaration

Following is the declaration for java.util.regex.Matcher.usePattern(Pattern newPattern) method.

public Matcher usePattern(Pattern newPattern)

Parameters

  • newPattern - The new pattern used by this matcher.

Return Value

this matcher.

Exceptions

  • IllegalArgumentException - If newPattern is null.

Example

The following example shows the usage of java.util.regex.Matcher.usePattern(Pattern newPattern) method.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatcherDemo {
   private static String REGEX = "(a*b)(foo)";
   private static String INPUT = "aabfooaabfooabfoob";

   public static void main(String[] args) {
      // create a pattern
      Pattern pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 
      while(matcher.find()) {
     //Prints the start index of the subsequence captured by the given group.
          System.out.println("Second Capturing Group, (foo) Match String start(): "+matcher.start(1));
      }  
      matcher.reset();
      matcher.usePattern(Pattern.compile("(a*b)(foob)"));
      while(matcher.find()) {
     //Prints the start index of the subsequence captured by the given group.
     System.out.println("Second Capturing Group, (fooab) Match String start(): "+matcher.start(1));
      }  
   }
}

Let us compile and run the above program, this will produce the following result −

Second Capturing Group, (foo) Match String start(): 0
Second Capturing Group, (foo) Match String start(): 6
Second Capturing Group, (foo) Match String start(): 12
Second Capturing Group, (fooab) Match String start(): 12

java.util.regex.Matcher.useTransparentBounds(boolean b) Method Example

Description

The java.util.regex.Matcher.useTransparentBounds(boolean b) method sets the transparency of region bounds for this matcher.

Declaration

Following is the declaration for java.util.regex.Matcher.useTransparentBounds(boolean b) method.

public Matcher useTransparentBounds(boolean b)

Parameters

  • b - a boolean indicating whether or not to use transparent bounds.

Return Value

this matcher.

Example

The following example shows the usage of java.util.regex.Matcher.useTransparentBounds(boolean b) method.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatcherDemo {
   private static final String REGEX = "(.*)(\\d+)(.*)";
   private static final String INPUT = "This is a sample Text, 1234, with numbers in between.";

   public static void main(String[] args) {
      // create a pattern
      Pattern pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 
      matcher.useTransparentBounds(true);
      System.out.println(matcher.hasTransparentBounds());
   }
}

Let us compile and run the above program, this will produce the following result −

true

java.util.regex - PatternSyntaxException Class

Introduction

The java.util.regex.PatternSyntaxException class represents a unchecked exception thrown to indicate a syntax error in a regular-expression pattern.

Class declaration

Following is the declaration for java.util.regex.PatternSyntaxException class −

public class PatternSyntaxException
   extends IllegalArgumentException

Constructors

S.N. Method & Description
1 PatternSyntaxException(String desc, String regex, int index)

Constructs a new instance of this class.

Class methods

S.N. Method & Description
1 String getDescription()

Retrieves the description of the error.

2 int getIndex()

Retrieves the error index.

3 String getMessage()

Returns a multi-line string containing the description of the syntax error and its index, the erroneous regular-expression pattern, and a visual indication of the error index within the pattern.

4 String getPattern()

Retrieves the erroneous regular-expression pattern.

Methods inherited

This class inherits methods from the following classes −

  • Java.lang.Throwable
  • Java.lang.Object

Example

The following example shows the usage of java.util.regex.Pattern.PatternSyntaxException class methods.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

public class PatternSyntaxExceptionDemo {
   private static String REGEX = "[";
   private static String INPUT = "The dog says meow " + "All dogs say meow.";
   private static String REPLACE = "cat";

   public static void main(String[] args) {

      try{
         Pattern pattern = Pattern.compile(REGEX);
         // get a matcher object
         Matcher matcher = pattern.matcher(INPUT); 
         INPUT = matcher.replaceAll(REPLACE);
      }catch(PatternSyntaxException e){
         System.out.println("PatternSyntaxException: ");
         System.out.println("Description: "+ e.getDescription());
         System.out.println("Index: "+ e.getIndex());
         System.out.println("Message: "+ e.getMessage());
         System.out.println("Pattern: "+ e.getPattern());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

PatternSyntaxException: 
Description: Unclosed character class
Index: 0
Message: Unclosed character class near index 0
[
^
Pattern: [

Java Regex - Examples Matching Characters

Following are various examples of matching characters using regular expression in java.

S.N. Construct & Matches
1 x

The character x

2 \\

The backslash character

3 \0n

The character with octal value 0n (0 ≤ n ≤ 7)

4 \0nn

The character with octal value 0nn (0 ≤ n ≤ 7)

5 \0mnn

The character with octal value 0mnn (0 ≤ m ≤ 3, 0 ≤ n ≤ 7)

6 \xhh

The character with hexadecimal value 0xhh

7 \uhhhh

The character with hexadecimal value 0xhhhh

8 \t

The tab character ('\u0009')

9 \n

The newline (line feed) character ('\u000A')

10 \r

The carriage-return character ('\u000D')

11 \f

The form-feed character ('\u000C')

Java Regex - Example - Character x Match

Description

The character x matches the x present in a text. Here x represents characters from A to Z and a to z.

Example

The following example shows the usage of character matching.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CharactersDemo {
   private static final String REGEX = "a";
   private static final String INPUT = "dbcabcabc";

   public static void main(String[] args) {
      // create a pattern
      Pattern pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      if(matcher.find()) {
         //Prints the start index of the match.
         System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 3

Java Regex - Example - Character \\ Match

Description

The character \\ matches the backslash character present in a text.

Example

The following example shows the usage of character matching.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CharactersDemo {
   private static final String REGEX = "\\";
   private static final String INPUT = "dbca\\bcabc";

   public static void main(String[] args) {
      // create a pattern
      Pattern pattern = Pattern.compile(Pattern.quote(REGEX));
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      if(matcher.find()) {
         //Prints the start index of the match.
         System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 4

Java Regex - Example - Character \0n Match

Description

The character \0n matches the character with octal value 0n (0 ≤ n ≤ 7).

Example

The following example shows the usage of character matching.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CharactersDemo {
   private static final String REGEX = "\\07";
   private static final String INPUT = "abc\007abc";

   public static void main(String[] args) {
      // create a pattern
      Pattern pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      if(matcher.find()) {
         //Prints the start index of the match.
         System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 3

Java Regex - Example - Character \0nn Match

Description

The character \0nn matches the character with octal value 0nn (0 ≤ n ≤ 7).

Example

The following example shows the usage of character matching.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CharactersDemo {
   private static final String REGEX = "\\007";
   private static final String INPUT = "abc\007abc";

   public static void main(String[] args) {
      // create a pattern
      Pattern pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      if(matcher.find()) {
         //Prints the start index of the match.
         System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 3

Java Regex - Example - Character \0mnn Match

Description

The character \0mnn matches the character with octal value 0mnn (0 ≤ m ≤ 3, 0 ≤ n ≤ 7).

Example

The following example shows the usage of character matching.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CharactersDemo {
   private static final String REGEX = "\\0101";
   private static final String INPUT = "abcAabc";

   public static void main(String[] args) {
      // create a pattern
      Pattern pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      if(matcher.find()) {
         //Prints the start index of the match.
         System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 3

Java Regex - Example - Character \0xhh Match

Description

The character \0xhh matches the character with hexadecimal value 0xhh.

Example

The following example shows the usage of character matching.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CharactersDemo {
   private static final String REGEX = "\\x41";
   private static final String INPUT = "abcAabc";

   public static void main(String[] args) {
      // create a pattern
      Pattern pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      if(matcher.find()) {
         //Prints the start index of the match.
         System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 3

Java Regex - Example - Character \0uhhhh Match

Description

The character \0uhhhh matches the character with unicode value 0uhhhh.

Example

The following example shows the usage of character matching.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CharactersDemo {
   private static final String REGEX = "\\u0041";
   private static final String INPUT = "abcAabc";

   public static void main(String[] args) {
      // create a pattern
      Pattern pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      if(matcher.find()) {
         //Prints the start index of the match.
         System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 3

Java Regex - Example - Character \t Match

Description

The character \t matches the tab character.

Example

The following example shows the usage of character matching.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CharactersDemo {
   private static final String REGEX = "\t";
   private static final String INPUT = "abc\tabc";

   public static void main(String[] args) {
      // create a pattern
      Pattern pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      if(matcher.find()) {
         //Prints the start index of the match.
         System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 3

Java Regex - Example - Character \n Match

Description

The character \n matches the newline character.

Example

The following example shows the usage of character matching.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CharactersDemo {
   private static final String REGEX = "\n";
   private static final String INPUT = "abc\nabc";

   public static void main(String[] args) {
      // create a pattern
      Pattern pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      if(matcher.find()) {
         //Prints the start index of the match.
         System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 3

Java Regex - Example - Character \r Match

Description

The character \r matches the carriage-return character.

Example

The following example shows the usage of character matching.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CharactersDemo {
   private static final String REGEX = "\r";
   private static final String INPUT = "abc\rabc";

   public static void main(String[] args) {
      // create a pattern
      Pattern pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      if(matcher.find()) {
         //Prints the start index of the match.
         System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 3

Java Regex - Example - Character \f Match

Description

The character \f matches the form-feed character.

Example

The following example shows the usage of character matching.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CharactersDemo {
   private static final String REGEX = "\f";
   private static final String INPUT = "abc\fabc";

   public static void main(String[] args) {
      // create a pattern
      Pattern pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      if(matcher.find()) {
         //Prints the start index of the match.
         System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 3

Java Regex - Examples Matching Character Classes

Following are various examples of matching character classes using regular expression in java.

S.N. Construct & Matches
1 [abc]

a, b, or c (simple class).

2 [^abc]

Any character except a, b, or c (negation).

3 [a-zA-Z]

a through z or A through Z, inclusive (range).

4 [a-d[m-p]]

a through d, or m through p: [a-dm-p] (union).

5 [a-z&&[def]]

d, e, or f (intersection).

6 [a-z&&[^bc]]

a through z, except for b and c: [ad-z] (subtraction)

7 [a-z&&[^m-p]]

a through z, and not m through p: [a-lq-z](subtraction).

Java Regex - Example - Character Class [abc] Match

Description

The character class [abc] matches a, b, or c.

Example

The following example shows the usage of character class matching.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CharacterClassDemo {
   private static final String REGEX = "[abc]";
   private static final String INPUT = "dbcabcabc";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
         //Prints the start index of the match.
         System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 4
Match String start(): 5
Match String start(): 6
Match String start(): 7
Match String start(): 8

Java Regex - Example - Character Class [^abc] Match

Description

The character class [^abc] matches any character except a, b, or c.

Example

The following example shows the usage of character class matching.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CharacterClassDemo {
   private static final String REGEX = "[^abc]";
   private static final String INPUT = "dbcabcabc";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
         //Prints the start index of the match.
         System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 0

Java Regex - Example - Character Class [a-zA-Z] Match

Description

The character class [a-zA-Z] matches any character from a to z or A to Z.

Example

The following example shows the usage of character class matching.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CharacterClassDemo {
   private static final String REGEX = "[a-zA-Z]";
   private static final String INPUT = "dbcabca124ADCbc";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
         //Prints the start index of the match.
         System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 0
Match String start(): 1
Match String start(): 2
Match String start(): 3
Match String start(): 4
Match String start(): 5
Match String start(): 6
Match String start(): 10
Match String start(): 11
Match String start(): 12
Match String start(): 13
Match String start(): 14

Java Regex - Example - Character Class [a-d[m-p]] Match

Description

The character class [a-d[m-p]] matches any character from a to d or m to p.

Example

The following example shows the usage of character class matching.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CharacterClassDemo {
   private static final String REGEX = "[a-d[m-p]]";
   private static final String INPUT = "dbcabca124ADCmnbc";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
         //Prints the start index of the match.
         System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 0
Match String start(): 1
Match String start(): 2
Match String start(): 3
Match String start(): 4
Match String start(): 5
Match String start(): 6
Match String start(): 13
Match String start(): 14
Match String start(): 15
Match String start(): 16

Java Regex - Example - Character Class [a-z&&[def]] Match

Description

The character class [a-z&&[def]] matches d,e or f.

Example

The following example shows the usage of character class matching.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CharacterClassDemo {
   private static final String REGEX = "[a-z&&[def]]";
   private static final String INPUT = "dbcabca124ADCmnbc";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
         //Prints the start index of the match.
         System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 0

Java Regex - Example - Character Class [a-z&&[^bc]] Match

Description

The character class [a-z&&[^bc]] matches any character from a to z except b and c.

Example

The following example shows the usage of character class matching.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CharacterClassDemo {
   private static final String REGEX = "[a-z&&[^bc]]";
   private static final String INPUT = "dbcabca124ADCmnbc";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
         //Prints the start index of the match.
         System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 0
Match String start(): 3
Match String start(): 6
Match String start(): 13
Match String start(): 14

Java Regex - Example - Character Class [a-z&&[^m-p]] Match

Description

The character class [a-z&&[^m-p]] matches any character from a to z except m to p.

Example

The following example shows the usage of character class matching.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CharacterClassDemo {
   private static final String REGEX = "[a-z&&[^m-p]]";
   private static final String INPUT = "dbcabca124ADCmnbc";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
         //Prints the start index of the match.
         System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 0
Match String start(): 1
Match String start(): 2
Match String start(): 3
Match String start(): 4
Match String start(): 5
Match String start(): 6
Match String start(): 15
Match String start(): 16

Java Regex - Examples Matching Predefined Character Classes

Following are various examples of matching predefined character classes using regular expression in java.

S.N. Construct & Matches
1 .

Any character (may or may not match line terminators).

2 \d

A digit: [0-9].

3 \D

A non-digit: [^0-9].

4 \s

A whitespace character: [ \t\n\x0B\f\r]

5 \S

A non-whitespace character: [^\s].

6 \w

A word character: [a-zA-Z_0-9].

7 \W

A non-word character: [^\w]

Java Regex - Example - Predefined Character Class . Match

Description

The character class . matches any character.

Example

The following example shows the usage of Predefined character class matching.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PredefinedCharacterClassDemo {
   private static final String REGEX = ".";
   private static final String INPUT = "dbcabcab12\tc";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
         //Prints the start index of the match.
         System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 0
Match String start(): 1
Match String start(): 2
Match String start(): 3
Match String start(): 4
Match String start(): 5
Match String start(): 6
Match String start(): 7
Match String start(): 8
Match String start(): 9
Match String start(): 10
Match String start(): 11

Java Regex - Example - Predefined Character Class \d Match

Description

The character class \d matches any digit from 0 to 9.

Example

The following example shows the usage of Predefined character class matching.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PredefinedCharacterClassDemo {
   private static final String REGEX = "\\d";
   private static final String INPUT = "dbcabcab12\tc";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
         //Prints the start index of the match.
         System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 8
Match String start(): 9

Java Regex - Example - Predefined Character Class \D Match

Description

The character class \D matches any non-digit.

Example

The following example shows the usage of Predefined character class matching.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PredefinedCharacterClassDemo {
   private static final String REGEX = "\\D";
   private static final String INPUT = "dbcabcab12\tc";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
         //Prints the start index of the match.
         System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 0
Match String start(): 1
Match String start(): 2
Match String start(): 3
Match String start(): 4
Match String start(): 5
Match String start(): 6
Match String start(): 7
Match String start(): 10
Match String start(): 11

Java Regex - Example - Predefined Character Class \s Match

Description

The character class \s matches any white-space character.

Example

The following example shows the usage of Predefined character class matching.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PredefinedCharacterClassDemo {
   private static final String REGEX = "\\s";
   private static final String INPUT = "dbcabcab12\tc";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
         //Prints the start index of the match.
         System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 10

Java Regex - Example - Predefined Character Class \S Match

Description

The character class \S matches any non white-space character.

Example

The following example shows the usage of Predefined character class matching.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PredefinedCharacterClassDemo {
   private static final String REGEX = "\\S";
   private static final String INPUT = "dbcabcab12\tc";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
         //Prints the start index of the match.
         System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 0
Match String start(): 1
Match String start(): 2
Match String start(): 3
Match String start(): 4
Match String start(): 5
Match String start(): 6
Match String start(): 7
Match String start(): 8
Match String start(): 9
Match String start(): 11

Java Regex - Example - Predefined Character Class \w Match

Description

The character class \s matches any word character from a to z or A to Z or 0 to 9.

Example

The following example shows the usage of Predefined character class matching.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PredefinedCharacterClassDemo {
   private static final String REGEX = "\\w";
   private static final String INPUT = "dbcaABb12\tc";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
         //Prints the start index of the match.
         System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 0
Match String start(): 1
Match String start(): 2
Match String start(): 3
Match String start(): 4
Match String start(): 5
Match String start(): 6
Match String start(): 7
Match String start(): 8
Match String start(): 10

Java Regex - Example - Predefined Character Class \W Match

Description

The character class \s matches any non-word character.

Example

The following example shows the usage of Predefined character class matching.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PredefinedCharacterClassDemo {
   private static final String REGEX = "\\W";
   private static final String INPUT = "dbcaABb12\tc";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
         //Prints the start index of the match.
         System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 9

Java Regex - Examples Matching POSIX Character Classes

Following are various examples of matching POSIX character classes using regular expression in java.

S.N. Construct & Matches
1 \p{Lower}

A lower-case alphabetic character: [a-z].

2 \p{Upper}

An upper-case alphabetic character:[A-Z].

3 \p{ASCII}

All ASCII:[\x00-\x7F].

4 \p{Alpha}

An alphabetic character:[\p{Lower}\p{Upper}].

5 \p{Digit}

A decimal digit: [0-9].

6 \p{Alnum}

An alphanumeric character:[\p{Alpha}\p{Digit}].

7 \p{Punct}

Punctuation: One of !"#$%&'()*+,-./:;<=>?@[\]^_>{|}<.

8 \p{Graph}

A visible character: [\p{Alnum}\p{Punct}].

9 \p{Print}

A printable character: [\p{Graph}\x20].

10 \p{Blank}

A space or a tab: [ \t].

11 \p{XDigit}

A hexadecimal digit: [0-9a-fA-F].

12 \p{Space}

A whitespace character: [ \t\n\x0B\f\r].

Java Regex - Example - Posix Character Class \p{Lower} Match

Description

The character class \p{Lower} matches any lower case character.

Example

The following example shows the usage of Posix character class matching.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PosixCharacterClassDemo {
   private static final String REGEX = "\\p{Lower}";
   private static final String INPUT = "dbcaABb12\tc";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
         //Prints the start index of the match.
         System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 0
Match String start(): 1
Match String start(): 2
Match String start(): 3
Match String start(): 6
Match String start(): 10

Java Regex - Example - Posix Character Class \p{Upper} Match

Description

The character class \p{Upper} matches any upper case character.

Example

The following example shows the usage of Posix character class matching.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PosixCharacterClassDemo {
   private static final String REGEX = "\\p{Upper}";
   private static final String INPUT = "dbcaABb12\tc";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
         //Prints the start index of the match.
         System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 4
Match String start(): 5

Java Regex - Example - Posix Character Class \p{ASCII} Match

Description

The character class \p{ASCII} matches any ascii character.

Example

The following example shows the usage of Posix character class matching.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PosixCharacterClassDemo {
   private static final String REGEX = "\\p{ASCII}";
   private static final String INPUT = "Bb12\tc";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
         //Prints the start index of the match.
         System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 0
Match String start(): 1
Match String start(): 2
Match String start(): 3
Match String start(): 4
Match String start(): 5

Java Regex - Example - Posix Character Class \p{Alpha} Match

Description

The character class \p{Alpha} matches any alphabetic character.

Example

The following example shows the usage of Posix character class matching.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PosixCharacterClassDemo {
   private static final String REGEX = "\\p{Alpha}";
   private static final String INPUT = "Bb12\tc";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
         //Prints the start index of the match.
         System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 0
Match String start(): 1
Match String start(): 5

Java Regex - Example - Posix Character Class \p{Digit} Match

Description

The character class \p{Digit} matches any digit.

Example

The following example shows the usage of Posix character class matching.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PosixCharacterClassDemo {
   private static final String REGEX = "\\p{Digit}";
   private static final String INPUT = "Bb12\tc";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
         //Prints the start index of the match.
         System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 2
Match String start(): 3

Java Regex - Example - Posix Character Class \p{Alnum} Match

Description

The character class \p{Alnum} matches any alphanumeric character.

Example

The following example shows the usage of Posix character class matching.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PosixCharacterClassDemo {
   private static final String REGEX = "\\p{Alnum}";
   private static final String INPUT = "Bb12\tc";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
         //Prints the start index of the match.
         System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 0
Match String start(): 1
Match String start(): 2
Match String start(): 3
Match String start(): 5

Java Regex - Example - Posix Character Class \p{Punct} Match

Description

The character class \p{Punct} matches any punctuation character.

Example

The following example shows the usage of Posix character class matching.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PosixCharacterClassDemo {
   private static final String REGEX = "\\p{Punct}";
   private static final String INPUT = "Bb12\tc!";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
         //Prints the start index of the match.
         System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 6

Java Regex - Example - Posix Character Class \p{Graph} Match

Description

The character class \p{Graph} matches any visible character.

Example

The following example shows the usage of Posix character class matching.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PosixCharacterClassDemo {
   private static final String REGEX = "\\p{Graph}";
   private static final String INPUT = "Bb12\tc!";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
         //Prints the start index of the match.
         System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 0
Match String start(): 1
Match String start(): 2
Match String start(): 3
Match String start(): 5
Match String start(): 6

Java Regex - Example - Posix Character Class \p{Print} Match

Description

The character class \p{Print} matches any printable character.

Example

The following example shows the usage of Posix character class matching.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PosixCharacterClassDemo {
   private static final String REGEX = "\\p{Print}";
   private static final String INPUT = "Bb12\tc!";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
         //Prints the start index of the match.
         System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 0
Match String start(): 1
Match String start(): 2
Match String start(): 3
Match String start(): 5
Match String start(): 6

Java Regex - Example - Posix Character Class \p{Blank} Match

Description

The character class \p{Blank} matches a space or tab character.

Example

The following example shows the usage of Posix character class matching.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PosixCharacterClassDemo {
   private static final String REGEX = "\\p{Blank}";
   private static final String INPUT = "Bb12\tc!";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
         //Prints the start index of the match.
         System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 4

Java Regex - Example - Posix Character Class \p{XDigit} Match

Description

The character class \p{XDigit} matches any hexadecimal character.

Example

The following example shows the usage of Posix character class matching.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PosixCharacterClassDemo {
   private static final String REGEX = "\\p{XDigit}";
   private static final String INPUT = "Bb12\tc!";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
         //Prints the start index of the match.
         System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 0
Match String start(): 1
Match String start(): 2
Match String start(): 3
Match String start(): 5

Java Regex - Example - Posix Character Class \p{Space} Match

Description

The character class \p{Space} matches any whitespace character.

Example

The following example shows the usage of Posix character class matching.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PosixCharacterClassDemo {
   private static final String REGEX = "\\p{Space}";
   private static final String INPUT = "Bb12 \tc!";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
         //Prints the start index of the match.
         System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 4
Match String start(): 5

Java Regex - Examples Matching JAVA Character Classes

Following are various examples of matching JAVA character classes using regular expression in java.

S.N. Construct & Matches
1 \p{javaLowerCase}

Equivalent to java.lang.Character.isLowerCase().

2 \p{javaUpperCase}

Equivalent to java.lang.Character.isUpperCase().

3 \p{javaWhitespace}

Equivalent to java.lang.Character.isWhitespace().

4 \p{javaMirrored}

Equivalent to java.lang.Character.isMirrored().

Java Regex - Example - JAVA Character Class \p{javaLowerCase} Match

Description

The character class \p{javaLowerCase} matches any lowercase character.

Example

The following example shows the usage of JAVA character class matching.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class JavaCharacterClassDemo {
   private static final String REGEX = "\\p{javaLowerCase}";
   private static final String INPUT = "Bb12 \tc!";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
         //Prints the start index of the match.
         System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 1
Match String start(): 6

Java Regex - Example - JAVA Character Class \p{javaUpperCase} Match

Description

The character class \p{javaUpperCase} matches any uppercase character.

Example

The following example shows the usage of JAVA character class matching.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class JavaCharacterClassDemo {
   private static final String REGEX = "\\p{javaUpperCase}";
   private static final String INPUT = "Bb12 \tc!";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
         //Prints the start index of the match.
         System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 0

Java Regex - Example - JAVA Character Class \p{javaWhitespace} Match

Description

The character class \p{javaWhitespace} matches any whitespace character.

Example

The following example shows the usage of JAVA character class matching.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class JavaCharacterClassDemo {
   private static final String REGEX = "\\p{javaWhitespace}";
   private static final String INPUT = "Bb12 \tc!";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
         //Prints the start index of the match.
         System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 4
Match String start(): 5

Java Regex - Example - JAVA Character Class \p{javaMirrored} Match

Description

The character class \p{javaMirrored} matches any mirrored character.

Example

The following example shows the usage of JAVA character class matching.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class JavaCharacterClassDemo {
   private static final String REGEX = "\\p{javaMirrored}";
   private static final String INPUT = "{Bb12 \tc!";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
         //Prints the start index of the match.
         System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 0

Java Regex - Examples Matching Unicode Character Classes

Following are various examples of matching Unicode character classes using regular expression in java.

S.N. Construct & Matches
1 \p{IsLatin}

A Latin script character.

2 \p{InGreek}

A character in the Greek block.

3 \p{Lu}

An uppercase letter.

4 \p{IsAlphabetic}

An alphabetic character (binary property).

5 \p{Sc}

A currency symbol.

6 \P{InGreek}

Any character except one in the Greek block.

7 [\p{L}&&[^\p{Lu}]]

Any letter except an uppercase letter.

Java Regex - Example - Unicode Character Class \p{IsLatin} Match

Description

The character class \p{IsLatin} matches any latin script character.

Example

The following example shows the usage of Unicode character class matching.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class UnicodeCharacterClassDemo {
   private static final String REGEX = "\\p{IsLatin}";
   private static final String INPUT = "Bb12 \tc!";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
         //Prints the start index of the match.
         System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 0
Match String start(): 1
Match String start(): 6

Java Regex - Example - Unicode Character Class \p{InGreek} Match

Description

The character class \p{InGreek} matches any greek block character.

Example

The following example shows the usage of Unicode character class matching.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class UnicodeCharacterClassDemo {
   private static final String REGEX = "\\p{InGreek}";
   private static final String INPUT = "[Bb12 \tc!\u03B1";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
         //Prints the start index of the match.
         System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 9

Java Regex - Example - Unicode Character Class \p{Lu} Match

Description

The character class \p{Lu} matches any uppercase character.

Example

The following example shows the usage of Unicode character class matching.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class UnicodeCharacterClassDemo {
   private static final String REGEX = "\\p{Lu}";
   private static final String INPUT = "[Bb12 \tc!\u03B1";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
         //Prints the start index of the match.
         System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 1

Java Regex - Example - Unicode Character Class \p{IsAlphabetic} Match

Description

The character class \p{IsAlphabetic} matches any alphabetic character.

Example

The following example shows the usage of Unicode character class matching.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class UnicodeCharacterClassDemo {
   private static final String REGEX = "\\p{IsAlphabetic}";
   private static final String INPUT = "[Bb12 \tc!\u03B1";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
         //Prints the start index of the match.
         System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 1
Match String start(): 2
Match String start(): 7
Match String start(): 9

Java Regex - Example - Unicode Character Class \p{Sc} Match

Description

The character class \p{Sc} matches any currency symbol.

Example

The following example shows the usage of Unicode character class matching.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class UnicodeCharacterClassDemo {
   private static final String REGEX = "\\p{Sc}";
   private static final String INPUT = "[Bb12 \tc$!\u03B1";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
         //Prints the start index of the match.
         System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 8

Java Regex - Example - Unicode Character Class \P{InGreek} Match

Description

The character class \P{InGreek} matches any character except greek symbols.

Example

The following example shows the usage of Unicode character class matching.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class UnicodeCharacterClassDemo {
   private static final String REGEX = "\\P{InGreek}";
   private static final String INPUT = "!\u03B1";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
         //Prints the start index of the match.
         System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 0

Java Regex - Example - Unicode Character Class [\p{L}&&[^\p{Lu}]] Match

Description

The character class [\p{L}&&[^\p{Lu}]] matches any character except uppercase letters.

Example

The following example shows the usage of Unicode character class matching.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class UnicodeCharacterClassDemo {
   private static final String REGEX = "[\\p{L}&&[^\\p{Lu}]]";
   private static final String INPUT = "!BSab\u03B1";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
         //Prints the start index of the match.
         System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 3
Match String start(): 4
Match String start(): 5

Java Regex - Examples of Boundary Matchers

Following are various examples of Boundary Matchers using regular expression in java.

S.N. Construct & Matches
1 ^

The beginning of a line.

2 $

The end of a line.

3 \b

A word boundary.

4 \B

A non-word boundary.

5 \A

The beginning of the input.

6 \G

The end of the previous match.

7 \Z

The end of the input but for the final terminator, if any.

8 \z

The end of the input.

Java Regex - Example - Boundry Matcher [^] Match

Description

The Boundry Matcher [^] matches the beginning of a line.

Example

The following example shows the usage of boundry matcher.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class BoundaryMatcherDemo {
   private static final String REGEX = "^";
   private static final String INPUT = "Welcome to TutorialsPoint.COM";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
        //Prints the start index of the match.
        System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 0

Java Regex - Example - Boundry Matcher [$] Match

Description

The Boundry Matcher [$] matches the end of a line.

Example

The following example shows the usage of boundry matcher.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class BoundaryMatcherDemo {
   private static final String REGEX = "$";
   private static final String INPUT = "Welcome to TutorialsPoint.COM";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
        //Prints the start index of the match.
        System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 29

Java Regex - Example - Boundry Matcher [\b] Match

Description

The Boundry Matcher [\b] matches the word boundary.

Example

The following example shows the usage of boundry matcher.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class BoundaryMatcherDemo {
   private static final String REGEX = "\\b";
   private static final String INPUT = "Welcome to TutorialsPoint.COM";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
        //Prints the start index of the match.
        System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 0
Match String start(): 7
Match String start(): 8
Match String start(): 10
Match String start(): 11
Match String start(): 25
Match String start(): 26
Match String start(): 29

Java Regex - Example - Boundry Matcher [\B] Match

Description

The Boundry Matcher [\B] matches the non-word boundary.

Example

The following example shows the usage of boundry matcher.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class BoundaryMatcherDemo {
   private static final String REGEX = "\\B";
   private static final String INPUT = "Welcome to TutorialsPoint.COM";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
        //Prints the start index of the match.
        System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 1
Match String start(): 2
Match String start(): 3
Match String start(): 4
Match String start(): 5
Match String start(): 6
Match String start(): 9
Match String start(): 12
Match String start(): 13
Match String start(): 14
Match String start(): 15
Match String start(): 16
Match String start(): 17
Match String start(): 18
Match String start(): 19
Match String start(): 20
Match String start(): 21
Match String start(): 22
Match String start(): 23
Match String start(): 24
Match String start(): 27
Match String start(): 28

Java Regex - Example - Boundry Matcher [\A] Match

Description

The Boundry Matcher [\A] matches the beginning of an input.

Example

The following example shows the usage of boundry matcher.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class BoundaryMatcherDemo {
   private static final String REGEX = "\\A";
   private static final String INPUT = "Welcome to TutorialsPoint.COM";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
        //Prints the start index of the match.
        System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 0

Java Regex - Example - Boundry Matcher [\G] Match

Description

The Boundry Matcher [\G] matches the end of previous match.

Example

The following example shows the usage of boundry matcher.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class BoundaryMatcherDemo {
   private static final String REGEX = "\\G";
   private static final String INPUT = "Welcome to TutorialsPoint.COM";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
        //Prints the start index of the match.
        System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 0

Java Regex - Example - Boundry Matcher [\Z] Match

Description

The Boundry Matcher [\Z] matches the end of the input but for the final terminator, if any.

Example

The following example shows the usage of boundry matcher.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class BoundaryMatcherDemo {
   private static final String REGEX = "\\Z";
   private static final String INPUT = "Welcome to TutorialsPoint.COM";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
        //Prints the start index of the match.
        System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 29

Java Regex - Example - Boundry Matcher [\z] Match

Description

The Boundry Matcher [\z] matches the end of the input.

Example

The following example shows the usage of boundry matcher.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class BoundaryMatcherDemo {
   private static final String REGEX = "\\z";
   private static final String INPUT = "Welcome to TutorialsPoint.COM";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
        //Prints the start index of the match.
        System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 29

Java Regex - Examples of Greedy Quantifiers

A greedy quantifier indicates to search engine to search the entire string and check whether it matches the given regexp. Following are various examples of Greedy Quantifiers using regular expression in java.

S.N. Construct & Matches
1 X?

X, once or not at all.

2 X*

X, zero or more times

3 X+

X, one or more times.

4 X{n}

X, exactly n times.

5 X{n,}

X, at least n times.

6 X{n,m}

X, at least n but not more than m times

Java Regex - Example - Greedy Quantifier [X?] Match

Description

The Greedy Quantifier [X?] matches the X present once or not present at all.

Example

The following example shows the usage of greedy quantifier.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class GreedyQuantifierDemo {
   private static final String REGEX = "T?";
   private static final String INPUT = "abcdTatW";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
        //Prints the start index of the match.
        System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 0
Match String start(): 1
Match String start(): 2
Match String start(): 3
Match String start(): 4
Match String start(): 5
Match String start(): 6
Match String start(): 7
Match String start(): 8

Java Regex - Example - Greedy Quantifier [X*] Match

Description

The Greedy Quantifier [X*] matches the X present zero or more times.

Example

The following example shows the usage of greedy quantifier.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class GreedyQuantifierDemo {
   private static final String REGEX = "T*";
   private static final String INPUT = "abcdTatW";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
        //Prints the start index of the match.
        System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 0
Match String start(): 1
Match String start(): 2
Match String start(): 3
Match String start(): 4
Match String start(): 5
Match String start(): 6
Match String start(): 7
Match String start(): 8

Java Regex - Example - Greedy Quantifier [X+] Match

Description

The Greedy Quantifier [X+] matches the X present one or more times.

Example

The following example shows the usage of greedy quantifier.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class GreedyQuantifierDemo {
   private static final String REGEX = "T+";
   private static final String INPUT = "abcdTatW";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
        //Prints the start index of the match.
        System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 4

Java Regex - Example - Greedy Quantifier [X{n}] Match

Description

The Greedy Quantifier [X{n}] matches the X present exactly n times.

Example

The following example shows the usage of greedy quantifier.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class GreedyQuantifierDemo {
   private static final String REGEX = "T{2}";
   private static final String INPUT = "abcdTatTTWTTT";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
        //Prints the start index of the match.
        System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 7
Match String start(): 10

Java Regex - Example - Greedy Quantifier [X{n,}] Match

Description

The Greedy Quantifier [X{n,}] matches the X present at least n times.

Example

The following example shows the usage of greedy quantifier.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class GreedyQuantifierDemo {
   private static final String REGEX = "T{2,}";
   private static final String INPUT = "abcdTatTTfgfgTTTW";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
        //Prints the start index of the match.
        System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 7
Match String start(): 13

Java Regex - Example - Greedy Quantifier [X{n,m}] Match

Description

The Greedy Quantifier [X{n,m}] matches the X present at least n but not more than m times.

Example

The following example shows the usage of greedy quantifier.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class GreedyQuantifierDemo {
   private static final String REGEX = "T{2,3}";
   private static final String INPUT = "abcdTatTTfgfgTTTtrtetTTTTW";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
        //Prints the start index of the match.
        System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 7
Match String start(): 13
Match String start(): 21

Java Regex - Examples of Reluctant Quantifiers

A reluctant quantifier indicates the search engine to start with the shortest possible piece of the string. Once match found, the engine continue; otherwise it adds one character to the section of the string being checked and search that, and so on. This process follows until it finds a match or the entire string has been used up. Following are various examples of Reluctant Quantifiers using regular expression in java.

S.N. Construct & Matches
1 X??

X, once or not at all.

2 X*?

X, zero or more times

3 X+?

X, one or more times.

4 X{n}?

X, exactly n times.

5 X{n,}?

X, at least n times.

6 X{n,m}?

X, at least n but not more than m times

Java Regex - Example - Reluctant Quantifier [X??] Match

Description

The Reluctant Quantifier [X??] matches the X present once or not present at all.

Example

The following example shows the usage of reluctant quantifier.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ReluctantQuantifierDemo {
   private static final String REGEX = "T??";
   private static final String INPUT = "abcdTatW";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
        //Prints the start index of the match.
        System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 0
Match String start(): 1
Match String start(): 2
Match String start(): 3
Match String start(): 4
Match String start(): 5
Match String start(): 6
Match String start(): 7
Match String start(): 8

Java Regex - Example - Reluctant Quantifier [X*?] Match

Description

The Reluctant Quantifier [X*?] matches the X present zero or more times.

Example

The following example shows the usage of reluctant quantifier.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ReluctantQuantifierDemo {
   private static final String REGEX = "T*?";
   private static final String INPUT = "abcdTatW";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
        //Prints the start index of the match.
        System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 0
Match String start(): 1
Match String start(): 2
Match String start(): 3
Match String start(): 4
Match String start(): 5
Match String start(): 6
Match String start(): 7
Match String start(): 8

Java Regex - Example - Reluctant Quantifier [X+?] Match

Description

The Reluctant Quantifier [X+?] matches the X present one or more times.

Example

The following example shows the usage of reluctant quantifier.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ReluctantQuantifierDemo {
   private static final String REGEX = "T+?";
   private static final String INPUT = "abcdTatW";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
        //Prints the start index of the match.
        System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 4

Java Regex - Example - Reluctant Quantifier [X{n}?] Match

Description

The Reluctant Quantifier [X{n}?] matches the X present exactly n times.

Example

The following example shows the usage of reluctant quantifier.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ReluctantQuantifierDemo {
   private static final String REGEX = "T{2}?";
   private static final String INPUT = "abcdTatTTWTTT";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
        //Prints the start index of the match.
        System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 7
Match String start(): 10

Java Regex - Example - Reluctant Quantifier [X{n,}?] Match

Description

The Reluctant Quantifier [X{n,}?] matches the X present at least n times.

Example

The following example shows the usage of reluctant quantifier.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ReluctantQuantifierDemo {
   private static final String REGEX = "T{2,}?";
   private static final String INPUT = "abcdTatTTfgfgTTTW";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
        //Prints the start index of the match.
        System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 7
Match String start(): 13

Java Regex - Example - Reluctant Quantifier [X{n,m}?] Match

Description

The Reluctant Quantifier [X{n,m}?] matches the X present at least n but not more than m times.

Example

The following example shows the usage of reluctant quantifier.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ReluctantQuantifierDemo {
   private static final String REGEX = "T{2,3}?";
   private static final String INPUT = "abcdTatTTfgfgTTTtrtetTTTTW";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
        //Prints the start index of the match.
        System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 7
Match String start(): 13
Match String start(): 21
Match String start(): 23

Java Regex - Examples of Possessive Quantifiers

A possessive quantifier is similar to greedy quantifier. It indicates the engine to start by checking the entire string.It is different in the sense if it doesn't work, if match failed and there is no looking back. Following are various examples of Possessive Quantifiers using regular expression in java.

S.N. Construct & Matches
1 X?+

X, once or not at all.

2 X*+

X, zero or more times

3 X++

X, one or more times.

4 X{n}+

X, exactly n times.

5 X{n,}+

X, at least n times.

6 X{n,m}+

X, at least n but not more than m times

Java Regex - Example - Possesive Quantifier [X?+] Match

Description

The Possesive Quantifier [X?+] matches the X present once or not present at all.

Example

The following example shows the usage of possesive quantifier.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PossesiveQuantifierDemo {
   private static final String REGEX = "T?+";
   private static final String INPUT = "abcdTatW";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
        //Prints the start index of the match.
        System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 0
Match String start(): 1
Match String start(): 2
Match String start(): 3
Match String start(): 4
Match String start(): 5
Match String start(): 6
Match String start(): 7
Match String start(): 8

Java Regex - Example - Possesive Quantifier [X*+] Match

Description

The Possesive Quantifier [X*+] matches the X present zero or more times.

Example

The following example shows the usage of possesive quantifier.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PossesiveQuantifierDemo {
   private static final String REGEX = "T*+";
   private static final String INPUT = "abcdTatW";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
        //Prints the start index of the match.
        System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 0
Match String start(): 1
Match String start(): 2
Match String start(): 3
Match String start(): 4
Match String start(): 5
Match String start(): 6
Match String start(): 7
Match String start(): 8

Java Regex - Example - Possesive Quantifier [X++] Match

Description

The Possesive Quantifier [X++] matches the X present one or more times.

Example

The following example shows the usage of possesive quantifier.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PossesiveQuantifierDemo {
   private static final String REGEX = "T++";
   private static final String INPUT = "abcdTatW";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
        //Prints the start index of the match.
        System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 4

Java Regex - Example - Possesive Quantifier [X{n}+] Match

Description

The Possesive Quantifier [X{n}+] matches the X present exactly n times.

Example

The following example shows the usage of possesive quantifier.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PossesiveQuantifierDemo {
   private static final String REGEX = "T{2}+";
   private static final String INPUT = "abcdTatTTWTTT";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
        //Prints the start index of the match.
        System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 7
Match String start(): 10

Java Regex - Example - Possesive Quantifier [X{n,}+] Match

Description

The Possesive Quantifier [X{n,}+] matches the X present at least n times.

Example

The following example shows the usage of Possesive quantifier.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ReluctantQuantifierDemo {
   private static final String REGEX = "T{2,}+";
   private static final String INPUT = "abcdTatTTfgfgTTTW";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
        //Prints the start index of the match.
        System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 7
Match String start(): 13

Java Regex - Example - Possesive Quantifier [X{n,m}+] Match

Description

The Possesive Quantifier [X{n,m}+] matches the X present at least n but not more than m times.

Example

The following example shows the usage of possesive quantifier.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PossesiveQuantifierDemo {
   private static final String REGEX = "T{2,3}+";
   private static final String INPUT = "abcdTatTTfgfgTTTtrtetTTTTW";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
        //Prints the start index of the match.
        System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 7
Match String start(): 13
Match String start(): 21

Java Regex - Examples of Logical Operators

Following are various examples of Logical Operators using regular expression in java.

S.N. Construct & Matches
1 XY

X followed by Y.

2 X|Y

Either X or Y.

Java Regex - Example - Logical Operator [XY] Match

Description

The Logical Operator [XY] matches the X followed by Y.

Example

The following example shows the usage of logical operator.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LogicalOperatorDemo {
   private static final String REGEX = "to";
   private static final String INPUT = "Welcome to TutorialsPoint.COM";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
        //Prints the start index of the match.
        System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 8
Match String start(): 13

Java Regex - Example - Logical Operator [X|Y] Match

Description

The Logical Operator [X|Y] matches the either X or Y.

Example

The following example shows the usage of logical operator.

package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LogicalOperatorDemo {
   private static final String REGEX = "t|o";
   private static final String INPUT = "Welcome to TutorialsPoint.COM";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
        //Prints the start index of the match.
        System.out.println("Match String start(): "+matcher.start());
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Match String start(): 4
Match String start(): 8
Match String start(): 9
Match String start(): 13
Match String start(): 14
Match String start(): 21
Match String start(): 24


Advertisements