Java中的模式类

PHPz
PHPz 转载
2023-08-30 09:01:02 282浏览

Java中的模式类

Pattern类表示正则表达式模式的编译版本。Pattern类位于java.util.regex包中。该类具有各种方法,用于匹配、拆分、搜索等各种操作。为了创建一个模式对象,需要使用compile方法。

语法

public static Pattern compile(String regex)

这里的regex代表一个正则表达式,它是一个字符串。为了编译它,我们使用这个方法。此外,这个编译对象可用于使用 Matcher 方法来匹配模式。

算法

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

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

  • 第二步 - 现在,使用compile方法编译模式。

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

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

  • 第五步 − 使用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"; // Add the input string to be matched

      boolean letsMatch = Pattern.matches(pattern, input);
      if (letsMatch) {
         System.out.println("Pattern matched.");
      } else {
         System.out.println("Pattern not matched.");
      }
   }
}

输出

Pattern matched.

说明

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

方法 2:使用 find() 方法

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

示例

在这个例子中,我们将使用find()方法来演示第二种方法。

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("Match found: " + matcher.group());
      }
   }
}

输出

Match found: 100
Match found: 3

方法1与方法2的比较

标准

方法 1

方法二

类型

字符串

字符串

方法

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

布尔查找()

方法逻辑

如果匹配成功则返回模式

返回匹配模式

结论

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

以上就是Java中的模式类的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除