Java 中的正则表达式 - Java Regex 示例

歡迎來到Java中的常規表現,它也被稱為Java中的Regex,當我開始編程時,Java的常規表現對我來說是一場噩夢,本教程旨在幫助你掌握Java中的常規表現,我也會回來更新我的Java的Regex學習。

Java 中的常规表达式

Regular Expression in Java, regex in java, java regex example, regex java, regular expression java The regular expression in java defines a pattern for a String. Regular Expression can be used to search, edit or manipulate text. A regular expression is not language specific but they differ slightly for each language. Regular Expression in Java is most similar to Perl. Java Regex classes are present in java.util.regex package that contains three classes:

  1. Pattern: Pattern 对象是常规表达式的编译版本。 Pattern 类没有任何公共构造者,我们使用它的公共静态方法 compile 通过通过常规表达式参数创建模式对象.
  2. Matcher: Matcher 是匹配输入 String 模式与创建模式对象的 java regex 引擎对象。

让我们来看看Java Regex的例子程序。

 1package com.journaldev.util;
 2
 3import java.util.regex.*;
 4
 5public class PatternExample {
 6
 7    public static void main(String[] args) {
 8    	Pattern pattern = Pattern.compile(".xx.");
 9    	Matcher matcher = pattern.matcher("MxxY");
10    	System.out.println("Input String matches regex - "+matcher.matches());
11    	// bad regular expression
12    	pattern = Pattern.compile("*xx*");
13
14    }
15
16}

当我们运行这个 java regex 示例程序时,我们会得到输出。

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

由于 Java 常规表达式围绕 String 旋转,所以 String 类在 Java 1.4 中被扩展,以提供一种匹配方法,使 regex 模式匹配。内部使用PatternMatcher Java regex 类来进行处理,但显然它减少了代码线条。

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

因此,如果你的要求只是检查输入字符串是否匹配模式,你应该通过使用简单的字符串匹配方法来节省时间和代码行。你应该只使用模式和匹配类,当你需要操纵输入字符串或需要重复使用模式时。 请注意,由regex定义的模式从左到右应用到字符串,一旦在匹配中使用源字符,它就不能重复使用。 例如,regex121只会匹配31212142121两次为_121____121

Java 中的常规表达式 - 常见匹配符号

QQ 常规表达式 QQ 描述 QQ 示例 QQ -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 当^是 [] 第 1个字符时,它否定了图案,匹配除 a, b 或 c → ("[^ab][^12]", "c3#") – true ("[^12]", "xcd3") – true ("[^ab][^12]", "c2") – false – == [a-e1-8] 相配在 a到 e 或 1到 8 个相配 相配("A-e1-3","d#") 相配("A-e1-3","2") 相配("A-e1-3","f2") 相配(" ") 相配("××") 相配("××","×"×") 相配("×","×"×") 相配("×","×") 相配("×") 相配("×") 相配("×") 相配("×"×") 相配("×") 相配("×") 相配("×") 相配("×") 相配) 相配(") 相配(") 相配("×"×"×"×"×") 相配) 相配(") 相配(") 相配(")

Java Regex 元字符

我们在Java regex中有一些元字符,这就像是通用匹配模式的短代码。

Regular ExpressionDescription
\dAny digits, short of [0-9]
\DAny non-digit, short for [^0-9]
\sAny whitespace character, short for [\t\n\x0B\f\r]
\SAny non-whitespace character, short for [^\s]
\wAny word character, short for [a-zA-Z_0-9]
\WAny non-word character, short for [^\w]
\bA word boundary
\BA non word boundary

有两种方法可以将元字符作为常规表达式中的普通字符。

将元字符以后冲突()先行。 2 保持元字符在 \Q(引用开始)和 \E(结束)内。

Java 中的常规表达式 - 量化

Java Regex 量化器指定要匹配的字符的发生次数。

Regular ExpressionDescription
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

例如, [abc]+ 意味着 - a, b, 或 c - 一次或多次. (abc)+ 意味着组 abc 再一次。

Java 中的常规表达式 - 捕捉组

在 Java 捕捉组中,常规表达式用于将多个字符作为单个单位处理。您可以使用 () 创建一个组。匹配捕捉组的输入字符串部分存储在内存中,可以使用 Backreference 召回。您可以使用 matcher.groupCount 方法来找出在 java regex 模式中捕捉组的数量。例如, ((a)(bc))包含 3 个捕捉组 - ((a)(bc)), (a) 和 (bc) 。

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

在第一个例子中,在 runtime第一个捕捉组是(\w\d)当与输入字符串a2a2匹配并保存到内存时评估到a2时,所以 \1是指a2,因此它返回了真。

例如,‘Pattern.CASE_INSENSITIVE’允许案例不敏感匹配 2. Pattern class还提供与 String class split() 方法类似的 split(String) 方法 3. Pattern class toString() 方法返回了这个模式编译的常规表达式 String 4. Matcher class 具有 start()end() 索引方法,可以准确地显示输入字符串中的匹配位置 。

让我们在一个简单的示例程序中看看这些Java regex方法。

 1package com.journaldev.util;
 2
 3import java.util.regex.Matcher;
 4import java.util.regex.Pattern;
 5
 6public class RegexExamples {
 7
 8    public static void main(String[] args) {
 9    	// using pattern with flags
10    	Pattern pattern = Pattern.compile("ab", Pattern.CASE_INSENSITIVE);
11    	Matcher matcher = pattern.matcher("ABcabdAb");
12    	// using Matcher find(), group(), start() and end() methods
13    	while (matcher.find()) {
14    		System.out.println("Found the text \"" + matcher.group()
15    				+ "\" starting at " + matcher.start()
16    				+ " index and ending at index " + matcher.end());
17    	}
18
19    	// using Pattern split() method
20    	pattern = Pattern.compile("\\W");
21    	String[] words = pattern.split("one@two#three:four$five");
22    	for (String s : words) {
23    		System.out.println("Split using Pattern.split(): " + s);
24    	}
25
26    	// using Matcher.replaceFirst() and replaceAll() methods
27    	pattern = Pattern.compile("1*2");
28    	matcher = pattern.matcher("11234512678");
29    	System.out.println("Using replaceAll: " + matcher.replaceAll("_"));
30    	System.out.println("Using replaceFirst: " + matcher.replaceFirst("_"));
31    }
32
33}

上面的Java regex示例程序的输出是。

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

Java Regex 起初看起来很困难,但如果你用它们工作了一段时间,它很容易学习和使用。

您可以从我们的 GitHub 存储库中查阅完整的代码和更常规的表达式示例。

Published At
Categories with 技术
Tagged with
comments powered by Disqus