Java 中的模式 LITERAL 欄位示例
支援對模式的直接解析。在此,所有字元(包括轉義序列和元字元)沒有任何特殊含義,它們都作為直接字元對待。
例如,通常,如果你在給定的輸入文字中搜索正則表示式“^This”,它將匹配以單詞“This”開頭的行。
示例 1
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LTERAL_Example {
public static void main(String[] args) {
String input = "This is the first line\n"
+ "This is the second line\n"
+ "^This is the third line";
//Regular expression to accept date in MM-DD-YYY format
String regex = "^This";
//Creating a Pattern object
Pattern pattern = Pattern.compile(regex,Pattern.LITERAL);
//Creating a Matcher object
Matcher matcher = pattern.matcher(input);
int count = 0;
while(matcher.find()) {
count++;
System.out.println(matcher.group());
}
System.out.println("Number of matches: "+count);
}
}
輸出
^This Number of matches: 1
在直接模式下,元字元“^”沒有意義,正則表示式“^This”匹配確切的單詞。
示例 2
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LTERAL_Example {
public static void main(String[] args) {
String input = "This is the first line\n"
+ "This is the second line\n"
+ "^This is the third line";
//Regular expression to accept date in MM-DD-YYY format
String regex = "^This";
//Creating a Pattern object
Pattern pattern = Pattern.compile(regex,Pattern.LITERAL);
System.out.println("Usually it is printed as: \n"+input);
//Creating a Matcher object
Matcher matcher = pattern.matcher(input);
int count = 0;
while(matcher.find()) {
count++;
System.out.println(matcher.group());
}
System.out.println("Number of matches: "+count);
}
}
輸出
Usually it is printed as: This is the first line This is the second line ^This is the third line ^This Number of matches: 1
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
安卓
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP