Java程序演示正则表达式中的转义字符
特殊字符,也称为元字符,在Java 正则表达式中具有特定的含义,如果您想将它们用作普通字符,则必须对其进行转义。
在这里,我们将通过 Java 程序演示正则表达式中的转义字符。但是,在深入探讨主题之前,让我们先熟悉一下 Java 中的正则表达式术语。
什么是正则表达式?
它是 **正则表达式** 的缩写。它是一个 API,允许用户定义字符串模式,这些模式可用于查找、修改和编辑字符串。正则表达式常用于定义字符串的限制,例如电子邮件验证和密码。**java.util.regex** 包包含正则表达式。
使用 \Q 和 \E 在正则表达式中转义字符
要转义字符,我们可以使用 \Q 和 \E 转义序列,它们以字母 Q 开头,以字母 E 结尾。字母 Q 和 E 之间的所有字符都将被转义。
假设您想转义字符串 **“Java”**,请将此字符串放在 \Q 和 \E 之间,如下所示:
\Qjava\E
示例
以下 Java 程序演示了如何在正则表达式中转义点(.)。
// Java Program to demonstrate how to escape characters in Java
// Regex Using \Q and \E for escaping
import java.io.*;
import java.util.regex.*;
//creation of a class named Regexeg1
public class Regexeg1 {
// Main method
public static void main(String[] args) {
// providing two strings as inputs
String s1 = "Tutorials.point";
String s2 = "Tutorialspoint";
//creation of an object of Pattern class with dot escaped
Pattern p1 = Pattern.compile("\\Q.\\E");
//creation of an object of Pattern class without escaping the dot
Pattern p2 = Pattern.compile(".");
// Matchers for every combination of patterns and strings
Matcher m1 = p1.matcher(s1);
Matcher m2 = p1.matcher(s2);
Matcher m3 = p2.matcher(s1);
Matcher m4 = p2.matcher(s2);
// find whether p1 and p2 match and display the Boolean value as a result
System.out.println("p1 matches s1: " + m1.find());
System.out.println("p1 matches s2: " + m2.find());
System.out.println("p2 matches s1: " + m3.find());
System.out.println("p2 matches s2: " + m4.find());
}
}
获得的输出为:
p1 matches s1: true p1 matches s2: false p2 matches s1: true p2 matches s2: true
使用反斜杠在正则表达式中转义字符
在 Java 正则表达式中转义特殊字符的主要方法是使用反斜杠。但是,由于反斜杠在 Java 字符串中也是转义字符,因此您需要在正则表达式模式中使用双反斜杠 (\\)。
例如,要匹配字符串“java.util.regex”,您的正则表达式模式将是:
java\.util\.regex
以上模式将把点(它是正则表达式中的特殊字符)视为一个简单的点。
示例
以下 Java 程序演示了如何使用反斜杠在正则表达式中转义字符。
// Java Program to demonstrate how to escape characters in Java
// Regex using backslash (\) for escaping
import java.util.regex.*;
public class Regexeg2 {
public static void main(String[] args) {
// creating string and a regex pattern
String text1 = "java.util.regex";
String regex1 = "java\\.util\\.regex";
// checking matches
System.out.println("Both String Matched: " + text1.matches(regex1));
}
}
以上代码的输出为:
Both String Matched: true
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP