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