×

Java String Matches vs Contains

String Matches in Java

The matches() function and its variations are used to determine whether or not a provided text matches a regular expression. The functioning as well as output of an expression remains the same where we supply two arguments: string and routine expression.

The matches() function has three versions, which are listed and described below:

String Matches()

By using this function, you may find out if the supplied string matches the regular expression. The outcome of using this function with the formed str.matches is exactly the same as that of the expression Pattern.matches (regex).

Syntax: 

public boolean matches(String regex) 

Return Type: Value Boolean, this value is true if and only if the given regular expression is satisfied by the strings; elsewhere, it is false.

Parameter: Use a regular expression to match a string.

Example:

public class TAE {
  // Main driver method
  public static void main(String args[])
  {
    // Declaration and initialization of a string
    String Str = new String("Welcome to tutorialandexample");
    // Shows a comment for better readability
    System.out.print(
      "Does String contains regex (.*)tutor(.*) ? : ");
    // Checking if regex is present or not
    System.out.println(Str.matches("(.*)tutor(.*)"));
    // Shows a comment for better readability
    System.out.print(
      "Does String contains regex tutor ? : ");
    // Checking if regex is present or not
    System.out.println(Str.matches("tutor"));
  }
}

Output:

Java String Matches vs Contains

String regionMatches()

Variants of regionMatches()method

RegionMatches(int toffset, int len, other, int offset)

RegionMatches(int toffset, other, ignore case, int offset, int len)

Parameters

regionMatches

Other:  The argument or comment of string is called other.

Int offset: The string parameter's string argument is the subregion's beginning offset.

int toffset:  The subregion's initial offset is included in this string.

Int len: Different type of characters for comparision.

Return Value

If the provided subregion of the string argument is satisfied by the given subregion of this string, this method returns true; otherwise, it returns false. The ignoreCase option determines that the matching is accurate or not.

Example:

public class Test {
   public static void main(String args[]) {
      String Str1 = new String("Welcome to tutorialandexample");
      String Str2 = new String("tutorialandexample");
      String Str3 = new String("TUTORIALANDEXAMPLE");
      System.out.print("Return Value :" );
      System.out.println(Str1.regionMatches(11, Str2, 0, 18));
      System.out.print("Return Value :" );
      System.out.println(Str1.regionMatches(11, Str3, 0, 18));
   }
}

OUTPUT

Java String Matches vs Contains

Syntax:

public boolean regionMatches(int str_strt, String other, int other_strt,int len)

String regionMatches() With ignoreCase

There are two ways to test whether 2 string parts are equal using this method.

Parameters

  • Int toffset: The subregion's initial offset is included in this string.
  • other:  the normal argument of string.
  • Int offset: The string parameter's string argument is the subregion's beginning offset.
  • Int len: Different type of characters for comparison.
  • ignoreCase: In that situation, while comparing with characters, disregard the case.

Return Value

It returns true if the string argument's stated subregion is satisfied by the subregion mentioned in this string; otherwise, it returns false. Whether or whether the matching is exact depends on the ignoreCase argument.

Example

public class Test {
   public static void main(String args[]) {
      String Str1 = new String("Welcome to Tutorialsandexample.com");//String first
      String Str2 = new String("TUTORIALS");//String Second
      System.out.print("Return Value :" );
      System.out.println(Str1.regionMatches(true, 11, Str2, 0, 9));
   }
}

Output

Java String Matches vs Contains

 

Syntax:

public boolean regionMatches(boolean ignoreCase, int toffset, offset, String other,int,int len)

Java String contains()

This string's character order is checked using the contains() function of the Java String class. If the string's series of char values can be discovered, it returns true; otherwise, it returns false.

Syntax

public boolean contains(CharSequence sequence)
Implementation:
public boolean contains(CharSequence sequence)
{
   return indexOf(sequence.toString()) > -1;
}

Here, the CharSequence is converted to a String before the indexOf function is used. If the String is found, the method indexOf returns zero or a larger number; otherwise, -1 is returned. The contains() function then returns true if a series of char values exists, else it returns false.

Example:

class dr{
public static void main(String args[])
{
String s1 = "My father is a DR.”
// True
System.out.println(s1.contains("DR."));


// False
System.out.println(s1.contains("er"));
}
}

Output:

Java String Matches vs Contains

Related Topics

Centered Square Numbers in Java

In this tutorial, we will understand how to check the number is a centered square number. It is one of the prevalent interview questions of IT companies. Firstly, we will...

3 minutes read.

How to Create an Immutable Class in Java

How to Create an Immutable Class in Java In Java, immutable means something that cannot be change. A class is called an immutable class if its content cannot be changed, once...

3 minutes read.

Java Return Keyword

The return keyword in Java is used to end a method's execution. the caller receives the return, followed by the appropriate value. The return type of the method, such as...

3 minutes read.

MessageDigest in Java

The compression of mathematical numbers is accomplished using hash functions. In almost every data security application, hash functions are employed. The hashing, often called has values, returns a value called...

3 minutes read.

Creating API Document Javadoc tool

The JavaDoc utility is a document generator tool written in Java that generates standard documentation in HTML format. It parses declarations and documentation in a source file collection that describes...

3 minutes read.

Difference Between in Java and C++

FeatureC++JavaDefinitionC++ is a general programming language created by Bjarne Stroustrup as an extension of c language    Java is class-based, object-based, and designed to have as few implementation dependencies as...

4 minutes read.

Array and String based questions in Java

1. What is an Array in Java? A collection of identical data types is referred to as an array. There can be no separate data kinds. It supports the storage of...

4 minutes read.

FizzBuzz Program in Java

FizzBuzz is a well-known children's game. This game helps children learn division. The FizzBuzz game is becoming a popular programming question, appearing frequently in Core Java interviews. This section will...

3 minutes read.

Java Enum

Enumerations are used in programming languages to represent collections of named constants. For instance, the four suits in a deck of playing cards might represent four iterators named Club, Diamond,...

3 minutes read.

Java Case Keyword

Case keyword: In this article we are going to learn the concept of a java case keyword.Generally, java case keyword is used with the switch statements.Case keyword is implemented in conditional...

3 minutes read.

XNOR operator in Java

The opposite of the binary equivalent of XOR is given by XNOR. Truth table: XYXNOR001010100111 If the bits are the same, it returns 1, else it returns 0. Examples:  Input: 10 20 Output : 1 A Binary...

3 minutes read.

Java Math round() Method

The round() method of Java Math class returns a long or an int value that is closest to the argument and is rounded to positive infinity. Syntax: public static int round(float a)public...

2 minutes read.

The Maximum Rectangular Area in a Histogram in Java

Continuous bars should be used to form the largest possible rectangle. We'll assume in the interest of convenience that each bar's width is 1. Naive Approach In this method, each bar will be...

6 minutes read.

Java File Input Stream

Java makes use of stream ideas to speed up input and output processes. All packages of input and output streams are contained in java.io.package. Stream: A stream is nothing more...

5 minutes read.

Java Math exp() Method

The exp() method of Math class returns Euler’s number(e) raised to the power of a double value. Syntax: public static double exp(double a) Parameters: The parameter ‘a’ represents the exponent e. Return Value: The exp ()...

2 minutes read.

MOOD Factors to Assess a Java Program

In this tutorial, we will comprehendthe meaning of mood factors in Java. For the development of any software system,the quality of anapplication is important. It is more important to maintain large-scale...

4 minutes read.

Java 9 Tutorial

The Java 9 is most popular release of java programming to make it platform modular. It is used to improve JDK and java implementation security. It provides JAVA SE and...

3 minutes read.

Adapter class in Java

By using the adapter classes, we can implement Listener interfaces. With the help of adapter classes, we can save code as it provides all implementation methods of listener interfaces Advantages of...

3 minutes read.

IdentityHashMap in Java

The IdentityHashMap class is comparable to the HashMap class and is an AbstractMap implementation. However, when comparing the key, it uses reference equality rather than object equality (or values). Identity HashMap...

6 minutes read.

Minimum Number of Taps to Open to Water a Garden in Java

Problem Statement The issue is that a gardener wants to water a (single-dimensional) garden using the fewest possible tap openings. The goal is to determine the minimum necessary taps to be...

8 minutes read.