Java 中的字符串匹配正则表达式
String 类是 Java 中最常用的类之一。它提供了许多方法来执行各种操作,在本文中,我们将讨论 String 类的 matches() 和 regionMatches() 方法。
在 Java 中使用 matches() 方法匹配字符串
matches() 方法将字符串与函数中传递的值匹配。作为参数传入函数的值应该是正则表达式。
Pattern.matches() 函数返回与 String.matches() 相同的结果。
在下面的示例中,我们创建了三个 String 变量,并使用 regex(正则表达式的缩写)来确定 String 中的所有字符是否都是小写且从 a 到 z 的有效字母。
第一个 print 语句调用 matches() 方法并传递 [a-z]+,如果字符是小写字母,则匹配的正则表达式。第一条语句输出 true,因为字符串 exampleStr1 包含与正则表达式匹配的字符。
第二条语句使用相同的正则表达式检查 exampleStr2 并返回 false,因为字符串的第一个字符是大写的。
最后的 print 语句还返回 false,检查 exampleStr3 是否存在非字母字符。
public class ExampleClass1 {
public static void main(String[] args) {
String exampleStr1 = "guardian";
String exampleStr2 = "Guardian";
String exampleStr3 = "[abc]";
System.out.println("First String: " + exampleStr1.matches("[a-z]+"));
System.out.println("Second String: " + exampleStr2.matches("[a-z]+"));
System.out.println("Third String: " + exampleStr3.matches("[a-z]+"));
}
}
输出:
First String: true
Second String: false
Third String: false
在 Java 中使用 regionMatches() 方法匹配字符串
另一种使用正则表达式匹配字符串的方法是 regionMatches(),它匹配两个字符串的区域。该示例有两个字符串,第一个是五个单词的语句,第二个字符串是一个单词。
使用 regionMatches() 方法,我们匹配单词 production 是否包含子字符串 duct。我们在 regionMatches() 函数中传递四个参数来执行此操作。
第一个参数是单词的起始位置,从哪里开始扫描;在我们的例子中,我们的单词在第 19 位,所以我们将它设置为起始位置。
第二个参数是我们想要匹配的 exampleStr2 输入字符串。
我们将 exampleStr2 的起始位置作为第三个参数传递,最后一个参数指定要匹配的字符数。
public class ExampleClass1 {
public static void main(String[] args) {
String exampleStr1 = "this site is in production";
String exampleStr2 = "duct";
System.out.println(exampleStr1.regionMatches(19, exampleStr2, 0, 4));
}
}
输出:
true
上面的代码仅在匹配的字符串大小写相同时才匹配子字符串。我们在 regionMatches() 中传递了另一个参数,它忽略了字符的大小写。
public class ExampleClass1 {
public static void main(String[] args) {
String exampleStr1 = "this site is in production";
String exampleStr2 = "DUCT";
System.out.println(exampleStr1.regionMatches(true, 19, exampleStr2, 0, 4));
}
}
输出:
true
Rupam Saini is an android developer, who also works sometimes as a web developer., He likes to read books and write about various things.
LinkedIn