Java 中的正則表達式 – Java Regex 示例

歡迎來到Java中的正則表達式。它也被稱為Java中的Regex。當我開始編程時,java正則表達式對我來說是一個噩夢。本教程旨在幫助您掌握Java中的正則表達式。我還會回來這裡來複習我的Java正則表達式知識。

Java中的正則表達式

Java中的正則表達式為字符串定義了一個模式。正則表達式可用於搜索、編輯或操作文本。正則表達式不是特定於語言的,但對於每種語言略有不同。Java中的正則表達式與Perl最相似。Java Regex類存在於java.util.regex包中,該包包含三個類:

  1. Pattern: Pattern對象是正則表達式的編譯版本。Pattern類沒有任何公共構造函數,我們使用它的公共靜態方法compile通過傳遞正則表達式參數來創建模式對象。
  2. 匹配器: 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類。請注意,由regex定義的模式是從左到右應用於字符串上的,一旦源字符在匹配中被使用,它就不能被重用。例如,regex“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 regex中有一些元字符,它就像是常見匹配模式的簡碼。

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 Regex一開始似乎很難,但如果你花一些時間與它們一起工作,學習和使用起來就會很容易。

你可以從我們的GitHub存儲庫中檢查完整的代碼和更多正則表達式示例。

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