Groovy - String matches() method
matches() method checks whether a String matches the given regular expression. It returns true if string matches else returns false.
Syntax
Boolean matches(String regex)
Parameters
regex − the expression for comparison.
Return Value
This method returns true if, and only if, this string matches the given regular expression.
Example - Matching Strings
Following is an example of the usage of matches() method.
Example.groovy
class Example {
static void main(String[] args) {
String str1 = "tutorials", str2 = "learning";
boolean retval = str1.matches(str2);
// method gets different values therefore it returns false
println("Value returned = " + retval);
retval = str2.matches("learning");
// method gets same values therefore it returns true
println("Value returned = " + retval);
retval = str1.matches("tuts");
// method gets different values therefore it returns false
println("Value returned = " + retval);
}
}
Output
When we run the above program, we will get the following result −
Value returned = false Value returned = true Value returned = false
Example - Matching Strings Using Pattern
Following is an example of the matches() method.
Example.groovy
class Example {
static void main(String[] args) {
String RegexExpression = "^[0-9]+";
println("The returned value is: " + "8785".matches(RegexExpression));
println("The returned value is: " + "@%*6575".matches(RegexExpression));
println("The returned value is: " + "675hjh".matches(RegexExpression));
}
}
Output
When we run the above program, we will get the following result −
The returned value is: true The returned value is: false The returned value is: false
Example - Checking if String contains only Alphabetic Characters
Following is an example of the matches() method.
Example.groovy
class Example {
static void main(String[] args) {
String RegexExpression = "[a-zA-Z ]+";
String s1 = "Tutorials Point is a reputed firm";
String s2 = "Tutori@ls && Po!nt is @ reputed f!rm";
String s3 = "Tutorials Point is a reputed firm 766868";
boolean Match1 = s1.matches("[a-zA-Z ]+");
boolean Match2 = s2.matches("[a-zA-Z ]+");
boolean Match3 = s3.matches("[a-zA-Z ]+");
println("Is the string having only alphabets: " + Match1);
println("Is the string having only alphabets: " + Match2);
println("Is the string having only alphabets: " + Match3);
}
}
Output
When we run the above program, we will get the following result −
Is the string having only alphabets: true Is the string having only alphabets: false Is the string having only alphabets: false
groovy_strings.htm
Advertisements