Computer >> Máy Tính >  >> Lập trình >> Java

Trường mẫu LITERAL trong Java với các ví dụ

Cho phép phân tích cú pháp theo nghĩa đen của mẫu. Trong điều này, tất cả các ký tự bao gồm chuỗi thoát và ký tự meta không có bất kỳ ý nghĩa đặc biệt nào, chúng được coi là ký tự chữ.

Ví dụ:thông thường nếu bạn tìm kiếm biểu thức chính quy “^ This” trong văn bản đầu vào nhất định, nó khớp với các dòng bắt đầu bằng từ "This" .

Ví dụ

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);
   }
}

Đầu ra

^This
Number of matches: 1

Ở chế độ nghĩa đen, ký tự siêu “^” không có nghĩa và biểu thức chính quy “^ This” khớp với từ chính xác.

Ví dụ

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);
   }
}

Đầu ra

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