我们提请您注意 Java 语言正则表达式简短指南的翻译,该指南由 Jeff Friesen 为 JavaWorld网站编写。为了方便阅读,我们将文章分为几个部分。
在 Java 程序中使用正则表达式 API 来识别和描述模式
Java 的字符和各种字符串数据类型为模式匹配提供低级支持,但将它们用于此目的通常会显着增加代码复杂性。通过使用 Regex API(“正则表达式 API”)可以获得更简单、性能更高的代码。本教程将帮助您开始使用正则表达式和 Regex API。我们将首先一般性地讨论包中三个最有趣的类java.util.regex
,然后查看该类的内部Pattern
并探索其复杂的模式匹配构造。 注意力: 您可以从此处下载本文演示应用程序的源代码(由 Jeff Friesen 为 JavaWorld 站点创建)。
什么是正则表达式?
正则表达式(regular expression/regex/regexp)是一个字符串,它是描述某组字符串的模式。该模式确定哪些行属于该集合。该模式由文字和元字符组成,即具有特殊含义而不是字面含义的字符。模式匹配是搜索文本以查找匹配项,即与正则表达式模式匹配的字符串。Java 通过其 Regex API 支持模式匹配。该 API 由三个类组成:Pattern
、Matcher
和PatternSyntaxException
,位于包中java.util.regex
:
- 类对象
Pattern
,也称为模板,是编译后的正则表达式。 - 类对象
Matcher
(或匹配器)是用于在字符序列(其类实现接口java.lang.CharSequence
并用作文本源的对象)中查找匹配项的模式解释机制。 - 类对象
PatternSyntaxException
用于描述无效的正则表达式模式。
java.lang.String
. 例如,仅当调用字符串与正则表达式完全匹配时,该函数boolean matches (String regex)
才会返回。 true
regex
便捷的方法 |
---|
matches() 类的其他面向正则表达式的便捷方法String 以类似于 Regex API 的方式在底层实现。 |
正则表达式演示
我创建了一个应用程序来演示 Java 正则表达式以及,和RegexDemo
的各种方法。以下是该演示应用程序的源代码。清单 1. 正则表达式演示 Pattern
Matcher
PatternSyntaxException
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
public class RegexDemo
{
public static void main(String[] args)
{
if (args.length != 2)
{
System.err.println("usage: java RegexDemo regex input");
return;
}
// Преобразуем символьные последовательности начала новой строки (\n) в символы начала строки.
args[1] = args[1].replaceAll("\\\\n", "\n");
try
{
System.out.println("regex = " + args[0]);
System.out.println("input = " + args[1]);
Pattern p = Pattern.compile(args[0]);
Matcher m = p.matcher(args[1]);
while (m.find())
System.out.println("Found [" + m.group() + "] starting at "
+ m.start() + " and ending at " + (m.end() - 1));
}
catch (PatternSyntaxException pse)
{
System.err.println("Неправильное регулярное выражение: " + pse.getMessage());
System.err.println("Описание: " + pse.getDescription());
System.err.println("Позиция: " + pse.getIndex());
System.err.println("Неправильный шаблон: " + pse.getPattern());
}
}
}
main
类 方法所做的第一件事RegexDemo
是检查其命令行。它需要两个参数:第一个是正则表达式,第二个是将在其中搜索正则表达式的输入文本。您可能需要在输入文本中使用换行符(\n)
。这只能通过指定字符\
后接字符来完成n
。该函数main()
将此字符序列转换为 Unicode 值 10。 大部分代码RegexDemo
包含在try-catch
. 该块try
首先输出给定的正则表达式和输入文本,然后创建一个Pattern
存储编译后的正则表达式的对象(编译正则表达式是为了提高模式匹配性能)。从对象中提取匹配器Pattern
并用于迭代搜索匹配项,直到找到所有匹配项。该块catch
调用几个类方法PatternSyntaxException
来检索有关异常的有用信息。该信息被顺序输出到输出流。目前还没有必要了解代码如何工作的细节:当我们在本文的第二部分研究 API 时,它们就会变得清晰。但是,您必须编译清单 1。获取清单 1 中的代码,然后在命令提示符处键入以下命令进行编译RegexDemo
: javac RegexDemo.java
Pattern 类及其构造
该类Pattern
是构成 Regex API 的三个类中的第一个,是正则表达式的编译表示。类 SDK 文档Pattern
描述了各种正则表达式构造,但如果您不积极使用正则表达式,则本文档的某些部分可能会令人困惑。什么是量词?贪婪量词、不情愿量词和占有量词之间有什么区别?什么是字符类、边界匹配器、反向引用和嵌入式标志表达式?我将在以下部分中回答这些问题和其他问题。
文字字符串
最简单的正则表达式构造是文字字符串。为了使模式匹配成功,输入文本的某些部分必须与该构造的模式匹配。考虑以下示例:java RegexDemo apple applet
在此示例中,我们尝试apple
在输入文本中查找模式的匹配项applet
。以下结果显示找到的匹配:
regex = apple
input = applet
Found [apple] starting at 0 and ending at 4
我们在输出中看到正则表达式和输入文本,然后apple
在小程序中看到成功检测的指示。另外,本场比赛的起始位置和结束位置分别为:0
和4
。开始位置表示文本中找到匹配项的第一个位置,结束位置表示匹配项的最后一个点。现在假设我们给出了以下命令行: java RegexDemo apple crabapple
这次我们得到以下结果,具有不同的开始和结束位置:
regex = apple
input = crabapple
Found [apple] starting at 4 and ending at 8
否则,使用 andapplet
作为正则表达式apple
- 输入文本,将找不到匹配项。整个正则表达式必须匹配,但在这种情况下,输入文本不包含t
after apple
。
元字符
更有趣的正则表达式结构将文字字符与元字符结合起来。例如,在正则表达式 中a.b
,点元字符(.)
表示a
和 b 之间的任何字符。请考虑以下示例: java RegexDemo .ox "The quick brown fox jumps over the lazy ox."
此示例既用作.ox
正则表达式又The quick brown fox jumps over the lazy ox.
用作输入文本。RegexDemo
在文本中搜索以任意字符开头并以 结尾的匹配项ox.
其执行结果如下:
regex = .ox
input = The quick brown fox jumps over the lazy ox.
Found [fox] starting at 16 and ending at 18
Found [ ox] starting at 39 and ending at 41
在输出中,我们看到两个匹配项:fox
和ox
(前面有一个空格字符)。元字符在第一种情况下.
匹配一个字符,在第二种情况下匹配一个空格。f
如果.ox
用元字符替换它会发生什么.
?也就是说,我们得到以下命令行的结果: java RegexDemo . "The quick brown fox jumps over the lazy ox."
由于点元字符匹配任何字符,因此RegexDemo
将输出输入文本的所有字符(包括尾随点字符)找到的匹配项:
regex = .
input = The quick brown fox jumps over the lazy ox.
Found [T] starting at 0 and ending at 0
Found [h] starting at 1 and ending at 1
Found [e] starting at 2 and ending at 2
Found [ ] starting at 3 and ending at 3
Found [q] starting at 4 and ending at 4
Found [u] starting at 5 and ending at 5
Found [i] starting at 6 and ending at 6
Found [c] starting at 7 and ending at 7
Found [k] starting at 8 and ending at 8
Found [ ] starting at 9 and ending at 9
Found [b] starting at 10 and ending at 10
Found [r] starting at 11 and ending at 11
Found [o] starting at 12 and ending at 12
Found [w] starting at 13 and ending at 13
Found [n] starting at 14 and ending at 14
Found [ ] starting at 15 and ending at 15
Found [f] starting at 16 and ending at 16
Found [o] starting at 17 and ending at 17
Found [x] starting at 18 and ending at 18
Found [ ] starting at 19 and ending at 19
Found [j] starting at 20 and ending at 20
Found [u] starting at 21 and ending at 21
Found [m] starting at 22 and ending at 22
Found [p] starting at 23 and ending at 23
Found [s] starting at 24 and ending at 24
Found [ ] starting at 25 and ending at 25
Found [o] starting at 26 and ending at 26
Found [v] starting at 27 and ending at 27
Found [e] starting at 28 and ending at 28
Found [r] starting at 29 and ending at 29
Found [ ] starting at 30 and ending at 30
Found [t] starting at 31 and ending at 31
Found [h] starting at 32 and ending at 32
Found [e] starting at 33 and ending at 33
Found [ ] starting at 34 and ending at 34
Found [l] starting at 35 and ending at 35
Found [a] starting at 36 and ending at 36
Found [z] starting at 37 and ending at 37
Found [y] starting at 38 and ending at 38
Found [ ] starting at 39 and ending at 39
Found [o] starting at 40 and ending at 40
Found [x] starting at 41 and ending at 41
Found [.] starting at 42 and ending at 42
引用元字符 |
---|
要将元字符或任何其他元字符指定. 为正则表达式构造中的文字字符,必须通过以下方式之一对其进行转义:
String regex = "\\."; 反斜杠(例如,\\. 或\\Q.\\E )。不要重复命令行参数中的反斜杠。 |
字符类
有时您必须将要查找的匹配项限制为特定字符集。例如,在文本中搜索元音a
、e
、i
和,每次出现元音字母o
都u
被视为匹配。在解决此类问题时,字符类将帮助我们定义方括号 ( [ ]
) 元字符之间的字符集。该类Pattern
支持简单字符类、范围类、逆、并、交集和减法类。我们现在来看看所有这些。
简单字符类
简单的字符类由并排放置的字符组成,并且仅匹配这些字符。例如,该类[abc]
匹配字符a
,b
和c
。考虑以下示例: java RegexDemo [csw] cave
正如您从结果中看到的,在此示例中只有c
与 中 匹配的字符cave
:
regex = [csw]
input = cave
Found [c] starting at 0 and ending at 0
倒排字符类
倒排字符类以元字符开头^
,并且仅匹配那些不包含在其中的字符。例如,该类匹配除,和[^abc]
之外的所有字符。请考虑以下示例: 请注意,在我的操作系统 (Windows) 上,需要双引号,因为 shell 将它们视为转义字符。正如您所看到的,在本示例中,仅找到了字符、和,它们在 中存在匹配: a
b
c
java RegexDemo "[^csw]" cave
^
a
v
e
cave
regex = [^csw]
input = cave
Found [a] starting at 1 and ending at 1
Found [v] starting at 2 and ending at 2
Found [e] starting at 3 and ending at 3
范围字符类
范围字符类由用连字符 (-
) 分隔的两个字符组成。从连字符左边的字符开始到右边的字符结束的所有字符都是该范围的一部分。例如,范围[a-z]
匹配所有小写拉丁字母。这相当于定义一个简单的类[abcdefghijklmnopqrstuvwxyz]
。考虑以下示例: 此示例将仅匹配在 中匹配的java RegexDemo [a-c] clown
字符: c
clown
regex = [a-c]
input = clown
Found [c] starting at 0 and ending at 0
Java 中的正则表达式,第 2 部分 Java 中的正则表达式,第 3 部分 Java 中的正则表达式,第 4 部分 Java 中的正则表达式,第 5 部分
GO TO FULL VERSION