×

Java Programs

Java Practice

Java program to search a pattern into the string using the lookingAt() method

Java example to search a pattern into the string using the lookingAt() method.
Submitted by Nidhi, on June 13, 2022

Problem statement

In this program, we will create a string and a regular expression pattern. Then we will use the lookingAt() method to check if a pattern exists in the string using the lookingAt() method. The lookingAt() method returns true, if a pattern exists in the string otherwise it returns false.

Source Code

The source code to search a pattern into the string using the lookingAt() method is given below. The given program is compiled and executed successfully.

// Java program to search a pattern into string 
// using lookingAt() method

import java.util.regex.*;

public class Main {
  public static void main(String[] args) {
    String str = "This is a string.";
    String regex = ".*is.*";

    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(str);

    boolean result = matcher.lookingAt();

    if (result)
      System.out.println("Pattern matched in string.");
    else
      System.out.println("Pattern did not match in string.");
  }
}

Output

Pattern matched in string.

Explanation

In the above program, we imported the "java.util.regex.*" package to use the Pattern and Matcher classes. Here, we created a public class Main.

The Main class contains a main() method. The main() method is the entry point for the program. Here we created a string and pattern. Then we used the compile(), lookingAt() methods to search for a pattern in the string and printed the appropriate message.

Java Regular Expressions Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.