Java中的正则表达式 – Java正则表达式示例

欢迎来到Java中的正则表达式。它在Java中也被称为Regex。当我开始编程时,Java正则表达式对我来说是一场噩梦。本教程旨在帮助您掌握Java中的正则表达式。我还会回到这里刷新我的Java Regex知识。

Java中的正则表达式

Java中的正则表达式定义了一个字符串的模式。正则表达式可用于搜索、编辑或操作文本。正则表达式并非特定于一种语言,但对于每种语言略有不同。Java中的正则表达式最类似于Perl。Java的Regex类位于java.util.regex包中,包含三个类:

  1. PatternPattern对象是正则表达式的已编译版本。Pattern类没有任何公共构造函数,我们使用它的公共静态方法compile,通过传递正则表达式参数来创建模式对象。
  2. Matcher: Matcher 是 Java 正则表达式引擎对象,用于将输入的字符串模式与创建的模式对象进行匹配。Matcher 类没有任何公共构造函数,我们使用模式对象的 matcher 方法获取 Matcher 对象,该方法以输入字符串作为参数。然后我们使用 matches 方法,根据输入字符串是否与正则表达式模式匹配,返回布尔结果。
  3. PatternSyntaxException: 如果正则表达式语法不正确,则会抛出 PatternSyntaxException

让我们来看一个 Java 正则表达式示例程序。

package com.journaldev.util;

import java.util.regex.*;

public class PatternExample {

	public static void main(String[] args) {
		Pattern pattern = Pattern.compile(".xx.");
		Matcher matcher = pattern.matcher("MxxY");
		System.out.println("Input String matches regex - "+matcher.matches());
		// 错误的正则表达式
		pattern = Pattern.compile("*xx*");

	}

}

当我们运行这个 Java 正则表达式示例程序时,我们会得到以下输出。

Input String matches regex - true
Exception in thread "main" java.util.regex.PatternSyntaxException: Dangling meta character '*' near index 0
*xx*
^
	at java.util.regex.Pattern.error(Pattern.java:1924)
	at java.util.regex.Pattern.sequence(Pattern.java:2090)
	at java.util.regex.Pattern.expr(Pattern.java:1964)
	at java.util.regex.Pattern.compile(Pattern.java:1665)
	at java.util.regex.Pattern.(Pattern.java:1337)
	at java.util.regex.Pattern.compile(Pattern.java:1022)
	at com.journaldev.util.PatternExample.main(PatternExample.java:13)

由于 Java 正则表达式围绕着字符串展开,因此在 Java 1.4 中扩展了 String 类,提供了一个 matches 方法来进行正则表达式模式匹配。在内部,它使用了 PatternMatcher Java 正则表达式类来进行处理,但显然它减少了代码行数。Pattern 类还包含一个 matches 方法,该方法接受正则表达式和输入字符串作为参数,并在匹配它们后返回布尔结果。因此,以下代码可用于在 Java 中匹配输入字符串与正则表达式。

String str = "bbb";
System.out.println("Using String matches method: "+str.matches(".bb"));
System.out.println("Using Pattern matches method: "+Pattern.matches(".bb", str));

所以如果您的要求只是检查输入字符串是否与模式匹配,您应该通过使用简单的字符串匹配方法来节省时间和代码行数。只有在需要操作输入字符串或需要重用模式时,才应使用Pattern和Matches类。请注意,由正则表达式定义的模式应用于字符串从左到右,一旦源字符在匹配中被使用,就不能被重用。例如,正则表达式“121”将仅在“31212142121”中匹配两次,如“_121____121”所示。

Java正则表达式-常见匹配符号

Regular Expression Description Example
. Matches any single character (“…”, “a%”) – true(“…”, “.a”) – true (“…”, “a”) – false
^aaa Matches aaa regex at the beginning of the line (“^a.c.”, “abcd”) – true (“^a”, “ac”) – false
aaa$ Matches regex aaa at the end of the line (“…cd$”, “abcd”) – true(“a$”, “a”) – true (“a$”, “aca”) – false
[abc] Can match any of the letter a, b or c. [] are known as character classes. (“^[abc]d.”, “ad9”) – true(“[ab].d$”, “bad”) – true (“[ab]x”, “cx”) – false
[abc][12] Can match a, b or c followed by 1 or 2 (“[ab][12].”, “a2#”) – true(“[ab]…[12]”, “acd2”) – true (“[ab][12]”, “c2”) – false
[^abc] When ^ is the first character in [], it negates the pattern, matches anything except a, b or c (“[^ab][^12].”, “c3#”) – true(“[^ab]…[^12]”, “xcd3”) – true (“[^ab][^12]”, “c2”) – false
[a-e1-8] Matches ranges between a to e or 1 to 8 (“[a-e1-3].”, “d#”) – true(“[a-e1-3]”, “2”) – true (“[a-e1-3]”, “f2”) – false
xx yy Matches regex xx or yy

Java正则表达式元字符

我们在Java正则表达式中有一些元字符,就像常见匹配模式的短代码一样。

Regular Expression Description
\d Any digits, short of [0-9]
\D Any non-digit, short for [^0-9]
\s Any whitespace character, short for [\t\n\x0B\f\r]
\S Any non-whitespace character, short for [^\s]
\w Any word character, short for [a-zA-Z_0-9]
\W Any non-word character, short for [^\w]
\b A word boundary
\B A non word boundary

有两种在正则表达式中将元字符用作普通字符的方法。

  1. 在元字符前加上反斜杠(\)。
  2. 将元字符保留在\Q(开始引号)和\E(结束引号)之间。

Java中的正则表达式 – 量词

Java正则表达式的量词用于指定要与之匹配的字符出现的次数。

Regular Expression Description
x? x occurs once or not at all
X* X occurs zero or more times
X+ X occurs one or more times
X{n} X occurs exactly n times
X{n,} X occurs n or more times
X{n,m} X occurs at least n times but not more than m times

Java正则表达式的量词也可以与字符类和捕获组一起使用。例如,[abc]+ 表示 – a、b 或 c – 出现一次或多次。而 (abc)+ 表示“abc”组出现一次或多次。我们将讨论 捕获组

Java中的正则表达式 – 捕获组

Java中的正则表达式捕获组用于将多个字符视为单个单元。您可以使用 () 创建一个组。与捕获组匹配的输入字符串部分将保存到内存中,并可以使用 反向引用 进行调用。您可以使用 matcher.groupCount 方法查找Java正则表达式模式中捕获组的数量。例如,((a)(bc)) 包含 3 个捕获组 – ((a)(bc))、(a) 和 (bc) 。您可以在正则表达式中使用带有反斜杠 (\) 的 反向引用,然后是要调用的组的编号。捕获组和反向引用可能会令人困惑,让我们通过一个示例来理解。

System.out.println(Pattern.matches("(\\w\\d)\\1", "a2a2")); //true
System.out.println(Pattern.matches("(\\w\\d)\\1", "a2b2")); //false
System.out.println(Pattern.matches("(AB)(B\\d)\\2\\1", "ABB2B2AB")); //true
System.out.println(Pattern.matches("(AB)(B\\d)\\2\\1", "ABB2B3AB")); //false

在第一个示例中,在运行时,第一个捕获组是 (\w\d),当与输入字符串 “a2a2” 匹配并保存在内存中时,评估为 “a2”。因此 \1 指的是 “a2”,因此返回 true。出于同样的原因,第二个语句打印 false。尝试自己理解语句 3 和 4 的情况。 🙂 现在我们将看一些 Pattern 和 Matcher 类的重要方法。

  1. 我们可以使用标志创建 Pattern 对象。例如 Pattern.CASE_INSENSITIVE 启用不区分大小写的匹配。
  2. Pattern 类还提供了类似于 String 类 split() 方法的 split(String) 方法。
  3. Pattern 类的 toString() 方法返回编译此模式的正则表达式字符串。
  4. Matcher 类具有 start()end() 索引方法,精确显示在输入字符串中找到匹配的位置。
  5. Matcher 类还提供字符串操作方法 replaceAll(String replacement)replaceFirst(String replacement)

让我们在一个简单的示例程序中查看这些 java 正则表达式方法。

package com.journaldev.util;

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

public class RegexExamples {

	public static void main(String[] args) {
		// 使用带标志的模式
		Pattern pattern = Pattern.compile("ab", Pattern.CASE_INSENSITIVE);
		Matcher matcher = pattern.matcher("ABcabdAb");
		// 使用 Matcher 的 find()、group()、start() 和 end() 方法
		while (matcher.find()) {
			System.out.println("Found the text \"" + matcher.group()
					+ "\" starting at " + matcher.start()
					+ " index and ending at index " + matcher.end());
		}

		// 使用 Pattern 的 split() 方法
		pattern = Pattern.compile("\\W");
		String[] words = pattern.split("one@two#three:four$five");
		for (String s : words) {
			System.out.println("Split using Pattern.split(): " + s);
		}

		// 使用 Matcher.replaceFirst() 和 replaceAll() 方法
		pattern = Pattern.compile("1*2");
		matcher = pattern.matcher("11234512678");
		System.out.println("Using replaceAll: " + matcher.replaceAll("_"));
		System.out.println("Using replaceFirst: " + matcher.replaceFirst("_"));
	}

}

上述 java 正则表达式示例程序的输出是。

Found the text "AB" starting at 0 index and ending at index 2
Found the text "ab" starting at 3 index and ending at index 5
Found the text "Ab" starting at 6 index and ending at index 8
Split using Pattern.split(): one
Split using Pattern.split(): two
Split using Pattern.split(): three
Split using Pattern.split(): four
Split using Pattern.split(): five
Using replaceAll: _345_678
Using replaceFirst: _34512678

这就是关于Java中的正则表达式的全部内容。Java正则表达式起初可能很难,但如果你花一些时间去学习和使用它们,就会发现它们很容易上手。

你可以从我们的GitHub仓库中查看完整的代码和更多的正则表达式示例。

Source:
https://www.digitalocean.com/community/tutorials/regular-expression-in-java-regex-example