Java 的 matches 方法用于判断字符串是否与用户指定的正则表达式匹配。根据结果,它将返回布尔值 True 或 False。
Java 编程语言中字符串 matches 的基本语法如下所示。以下 matches 方法将接受正则表达式作为参数,并检查原始字符串是否与该表达式匹配。
public boolean matches(String regexp); // It will return boolean True or False //In order to use in program String_Object.matches(String regexp);
Java String matches 示例
在此程序中,我们使用 matches 方法来检查此字符串是否与用户指定的表达式完全匹配。
package StringFunctions;
public class MatchMethod {
public static void main(String[] args) {
String str = "Learn Java at Tutorial Gateway";
String str1 = "We are abc working at abc Company";
String str2 = "We are abc working at abc Company";
boolean bool1 = str1.matches("abc");
boolean bool2 = str1.matches(str2);
boolean bool3 = str.matches("Learn Java(.*)");
boolean bool4 = str.matches("(.*)Java(.*)");
System.out.println("Does String str1 Matches with 'abc'? = " + bool1);
System.out.println("Does String str1 Matches with str2? = " + bool2);
System.out.println("Does String str1 Matches with RegExp? = " + bool3);
System.out.println("Does String str1 Matches with RegExp? = " + bool4);
}
}

以下语句将调用 public boolean matches (String regex) 方法来检查字符串 str1 是否与“abc”匹配。从上面的屏幕截图中,您可以发现它返回 False,因为它们不匹配。
boolean bool1 = str1.matches("abc");
它将检查 str 是否等于“Learn (.*)”或不。这意味着字符串应以 Learn 开头,并接受其后的任何内容。
boolean bool3 = str.matches("Learn Java(.*)");
以下语句将检查 str 是否与“(.*)”匹配或不。这意味着字符串必须包含 Java,并且它将接受该词之前或之后的所有内容。
boolean bool4 = str.matches("(.*)Java(.*)");
最后,我们使用了 Java System.out.println 语句来打印输出。
Java String matches 示例
在此 Java 程序中,我们将要求用户输入任何单词。根据用户输入的字符串值,此 String 函数将显示消息。
package StringFunctions;
import java.util.Scanner;
public class MatchMethodex {
private static Scanner sc;
public static void main(String[] args) {
sc = new Scanner(System.in);
System.out.println("Please Enter any word: ");
String str = sc.nextLine();
if (str.matches("(.*)team(.*)")) {
System.out.println("Hey!! Welcome to Programming Language");
}
else {
System.out.println("Goodbye Tutorial Gateway");
}
}
}
Please Enter any word:
Searching for team functions
Hey!! Welcome to Programming Language
让我们输入一个不同的单词。
Please Enter any word:
Search SQL server
Goodbye Tutorial Gateway
在此 matches 方法示例中,以下语句将要求用户输入任何单词或字符串。然后我们将用户输入的值赋给 str。
System.out.println("Please Enter any word: ");
String str = sc.nextLine();
接下来,我们使用 If Else 语句来检查用户输入的字符串是否与“(.*)team (.*)”匹配或不。这意味着字符串必须包含 team,并且它将接受该词之前或之后的所有内容。
- 如果 If 语句内的语句为 True,则打印 System.out.println(“Hey!! Welcome to Programming Language”); 语句。
- 否则,打印 System.out.println(“Goodbye to Tutorials”); 语句。