Java Regex to Exclude a Specific String Constant



In this program, we will use a regular expression to check if a given string does not contain the substring "kk" using Java. The regular expression ^((?!kk).)*$ is designed to match strings that do not include the "kk" pattern anywhere in the string. The program will evaluate a sample string and print whether or not it contains "kk".

Problem Statement

Write a program in Java for checking whether a given string contains the substring "kk." If the string does not contain "kk" the program will return true otherwise it will return false.

Input

String s = "tutorials"

Output

true

Steps to exclude a specific string constant

Following are the steps to exclude a specific String constant ?

  • Define a sample string create a string variable s and assign it a value.
  • Use a regular expression for matching using the matches() method to check if the string does not contain "kk" by utilizing the regex pattern ^((?!kk).)*$.
  • After that we will store the result of the match operation in a boolean variable i.
  • Print the boolean result to the console, which will indicate whether the string contains "kk" (false) or not (true).

regex ^((?!kk).)*$ returns true if a line does not contain kk, otherwise returns false

Example

public class RegTest {
   public static void main(String[] args) {
      // TODO Auto-generated method stub
      String s="tutorials";
      boolean i=s.matches("^((?!kk).)*$");
      System.out.println(i);
   }
}

Code explanation 

The program above begins by defining a string s with the value "tutorials." It then checks if this string matches the regular expression ^((?!kk).)*$, which returns true if "kk" is absent from the string. The matches() method is used to perform the regex check, and the result is stored in the boolean variable i. Finally, the result is printed to the console. Since the string "tutorials" does not contain "kk", the output will be true.

Updated on: 2024-09-29T02:51:09+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements