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 } }
true
false
regionMatches():
This method tests if 2 string are equal or not. It is implemented in 2 ways.
- boolean regionMatches(int toffset,String other,int ooffset,int len)
- 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]
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.