Java 中的模式类

javaobject oriented programmingprogramming更新于 2024/11/9 0:44:17

模式类表示为正则表达式模式的编译版本。模式类在 java.util.regex 包中提供。此类具有各种方法,可用于各种操作,如匹配、拆分、搜索等。为了创建模式对象,使用编译方法。

语法

public static Pattern compile(String regex)

此处,regex 表示正则表达式,即字符串。为了编译它,我们使用这种方法。此外,此编译对象可用于使用 Matcher 方法匹配模式。

算法

要编译和匹配模式,请按照以下步骤操作 -

  • 步骤 1 - 使用字符串初始化正则表达式模式。

  • 步骤 2 - 现在,使用编译方法编译模式。

  • 步骤 3 - 定义要与模式匹配的输入字符串。

  • 步骤 4 - 创建 Matcher 对象并将模式应用于输入字符串。

  • 步骤 5 - 使用 Matcher 方法执行各种操作

语法

public class Regex {
   public static void main(String[] args) {
      String pattern = "String1";
      Pattern compiledPattern = Pattern.compile(pattern);
      String input = "Strin2";
      Matcher matcher = compiledPattern.matcher(input);
      if (matcher.find()) {
         System.out.println("Match found: " + matcher.group(0));
         System.out.println("Captured group: " + matcher.group(1));
      } else {
         System.out.println("No match found.");
      }
   }
}

方法 1:使用 matches() 方法

此方法涉及使用 matches() 方法。

示例

import java.util.regex.Pattern;

public class MatchThePattern {
   public static void main(String[] args) {
      String pattern = "Hello (\w+)";
      String input = "Hello World"; // 添加要匹配的输入字符串

      boolean letsMatch = Pattern.matches(pattern, input);
      if (letsMatch) {
         System.out.println("模式匹配。");
      } else {
         System.out.println("模式不匹配。");
      }
   }
}

输出

模式匹配。

解释

通过将两个字符串输入作为参数传递给 matches 方法,我们可以成功匹配上述代码中的两个字符串模式。

方法 2:使用 find() 方法

find() 方法返回布尔类型并查找与模式匹配的表达式。以下是代码示例 −

示例

在此示例中,我们将使用 find() 方法演示方法 2。

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LetsFindPattern {
   public static void main(String[] args) {
      String pattern = "\b\d+\b";
      String input = "The price is 100 dollars for 3 items.";
      Pattern compiledPattern = Pattern.compile(pattern);
      Matcher matcher = compiledPattern.matcher(input);
      while (matcher.find()) {
         System.out.println("匹配结果: " + matcher.group());
      }
   }
}

输出

匹配结果:100
匹配结果:3

方法 1 与方法 2 的比较

条件

方法 1

方法 2

类型

字符串

字符串

方法

布尔匹配(字符串正则表达式)

布尔查找()

方法逻辑

如果匹配则返回模式

返回匹配模式

结论

正则表达式用于匹配模式。上述方法是匹配模式应采取的操作的示例。我们还通过两个工作示例演示了这些方法,展示了它们的功能和多功能性。通过了解这些方法及其用例,您可以使用正则表达式有效地找到匹配的模式。


相关文章


有用资源