String methods – matches and regionMatches

In this post, we will discuss about the String methods – matches and regionMatches.

boolean matches(String regex):

It returns true if String matches the given regular expression.

regex – the regular expression to which this string is to be matched.

It throws PatternSyntaxException – if the regular expression’s syntax is invalid.

public class ExampMatches {
	public static void main(String[] args) {
		
		String ip = "This is a house";
		
		System.out.println(ip.matches(".* is .*"));  // returns true 
		System.out.println(ip.matches(".* are .*"));  // returns false 	
	}
}
Output:
true
false

 

regionMatches():

This method tests if 2 string are equal or not. It is implemented in 2 ways.

  1. boolean regionMatches(int toffset,String other,int ooffset,int len)
  2. boolean regionMatches(boolean ignoreCase,int toffset,String other,int ooffset,int len)

boolean regionMatches(int toffset,String other,int ooffset,int len):

A substring of the String object is compared to a substring of the another string. The result is true if these substrings represent identical character sequences.

public class ExampRegionMatches {
	public static void main(String[] args) {
		
		String str1 = "This is a house";
		String str2  = "This";
				
		System.out.println(str1.regionMatches(0, str2, 0, 4));  // returns true .compare this
		System.out.println(str1.regionMatches(5, str2, 0, 4));  // returns false starts from 5th char
	}
}

Output:
true
false
[/su_note]

Ask Question
If you have any question, you can go to menu ‘Features -> Q&A forum-> Ask Question’.Select the desired category and post your question.
Avatar photo

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...

1 Response

  1. Sandeep says:

    The way of explanation for each and every concept is very good , but small suggestion from my end is like it’s better if we can have much clear explanation (writing comments for each and every line of code) about programs which we have as examples in each and every concept.