Java 正则表达式 API

Java Regex API 提供 1 个接口和 3 个类:

  • Pattern - 指定为字符串的正则表达式必须首先编译为此类的实例。然后可以使用生成的模式创建一个 Matcher对象,该对象可以将任意字符序列与正则表达式进行匹配。
Pattern p = Pattern.compile("abc");
Matcher m = p.matcher("abcabcabcd");
boolean b = m.matches(); //true
  • Matcher - 此类提供执行匹配操作的方法。
  • MatchResult(接口) - 它是匹配操作的结果。它包含用于确定与正则表达式匹配的结果的查询方法。
  • PatternSyntaxException - 这是一个未经检查的异常,用于指示正则表达式模式中的语法错误。

Pattern

编译后,它的实例可用于创建一个Matcher对象,该对象可以将行/字符串与正则表达式进行匹配。
处理期间的状态信息保存在“Matcher”实例中。
此类的实例是不可变的,并且可以安全地由多个并发线程使用。

  • Predicate asPredicate() - 创建可用于匹配字符串的 Java 8 谓词。
  • static Pattern compile(String regex) - 用于将给定的正则表达式编译成模式。
  • static Pattern compile(String regex, int flags) - 用于将给定的正则表达式编译成具有给定标志的模式。
  • int flags() - 用于返回此模式的匹配标志。
  • Matcher matcher(CharSequence input) - 它用于创建一个匹配器,将给定的输入与此模式进行匹配。
  • static boolean matches(字符串正则表达式,字符序列输入) - 它用于编译给定的正则表达式并尝试将给定的输入与其匹配。
  • String pattern() - 用于返回编译此模式的正则表达式。
  • static String quote(String s) - 它用于返回指定字符串的文字模式字符串。
  • String[] split(CharSequence input) - 它用于围绕此模式的匹配拆分给定的输入序列。
  • String[] split(CharSequence input, int limit) - 它用于围绕此模式的匹配拆分给定的输入序列。
  • Stream splitAsStream(CharSequence input) - 从给定的输入序列围绕此模式的匹配创建一个流。

Matcher

它是通过解释 Pattern对字符串/行执行匹配操作的主要类。
创建后,匹配器可用于执行不同类型的匹配操作。

此类的实例不是线程安全的。

  • boolean find() - 主要用于搜索文本中多次出现的正则表达式。
  • boolean find(int start) - 它用于从给定索引开始搜索文本中正则表达式的出现。
  • int start() - 它用于获取使用 find() 方法找到的匹配项的起始索引。
  • int end() - 它用于获取使用 find() 方法找到的匹配项的结束索引。它返回最后一个匹配字符旁边的字符索引。
  • int groupCount() - 用于查找匹配子序列的总数。
  • String group() - 用于查找匹配的子序列。
  • boolean match() - 用于测试正则表达式是否与模式匹配。
  • booleanlookingAt() - 尝试匹配输入序列,从区域的开头开始,与模式相匹配。
  • String quoteReplacement(String s) - 返回指定字符串的文字替换字符串。
  • Matcher reset() - 重置这个匹配器。
  • MatchResult toMatchResult() - 将此匹配器的匹配状态作为 MatchResult返回。

常用正则表达式示例

电子邮件地址的正则表达式

^[a-zA-Z0-9_!#$%&'*+/=?`{|}~^.-]+@[a-zA-Z0-9.-]+$

密码验证的正则表达式

在java中使用正则表达式匹配密码

((?=.*[a-z])(?=.*d)(?=.*[@#$%])(?=.*[A-Z]).{6,16})

国际电话号码的正则表达式

在java中使用正则表达式匹配国际电话号码

^\+(?:[0-9] ?){6,14}[0-9]$

日期格式的正则表达式

在java中使用正则表达式匹配日期格式

^[0-3]?[0-9]/[0-3]?[0-9]/(?:[0-9]{2})?[0-9]{2}$
Java 正则表达式
www. On IT Road .com

在Java中使用正则表达式进行匹配示例

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main 
{
 public static void main(String[] args) 
 {
  Pattern pattern = Pattern.compile("Java|Python");
  Matcher matcher = pattern.matcher("Generally, Java and python are good programming languages.");

  while (matcher.find()) {
            System.out.print("Start index: " + matcher.start());
            System.out.print(" End index: " + matcher.end() + " ");
            System.out.println(" - " + matcher.group());
        }
 }
}
日期:2020-09-17 00:10:19 来源:oir作者:oir