Metaký tự “^” khớp với đầu của một chuỗi cụ thể, tức là nó khớp với ký tự đầu tiên của chuỗi. Ví dụ:
- Biểu thức “^\\d” khớp chuỗi/dòng bắt đầu bằng chữ số.
- Biểu thức “^[a-z]” khớp chuỗi/dòng bắt đầu bằng chữ cái thường.
Ví dụ 1
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String args[]) {
// Đọc chuỗi từ người dùng
System.out.println("Nhập một chuỗi");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String regex = "^[^a-zA-Z0-9//s].*";
// Biên dịch biểu thức chính quy
Pattern pattern = Pattern.compile(regex);
// Lấy đối tượng matcher
Matcher matcher = pattern.matcher(input);
if (matcher.matches()) {
System.out.println("Khớp xảy ra");
} else {
System.out.println("Không khớp");
}
}
}
Kết quả
Nhập một chuỗi #starting with a special character Khớp xảy ra
Ví dụ 2
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
public static void main(String args[]) {
String regex = "\\.$";
Scanner sc = new Scanner(System.in);
System.out.println("Nhập 5 chuỗi đầu vào: ");
String input[] = new String[5];
for (int i = 0; i < 5; i++) {
input[i] = sc.nextLine();
}
// Tạo đối tượng Pattern
Pattern p = Pattern.compile(regex);
for (int i = 0; i < 5; i++) {
// Tạo đối tượng Matcher
Matcher m = p.matcher(input[i]);
if (m.find()) {
System.out.println("Chuỗi " + i + " kết thúc bằng '.'");
}
}
}
}
Kết quả
Nhập 5 chuỗi đầu vào: hello how are you. where do you live what is your name. welcome to tutorialspoint The Biggest Online Tutorials Library. Chuỗi 0 kết thúc bằng '.' Chuỗi 2 kết thúc bằng '.' Chuỗi 4 kết thúc bằng '.'
Ví dụ 3
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
public static void main(String args[]) {
String regex = "^[A-Z]";
Scanner sc = new Scanner(System.in);
System.out.println("Nhập 5 chuỗi đầu vào: ");
String input[] = new String[5];
for (int i = 0; i < 5; i++) {
input[i] = sc.nextLine();
}
// Tạo đối tượng Pattern
Pattern p = Pattern.compile(regex);
for (int i = 0; i < 5; i++) {
// Tạo đối tượng Matcher
Matcher m = p.matcher(input[i]);
if (m.find()) {
System.out.println("Chuỗi " + i + " bắt đầu bằng chữ hoa");
}
}
}
}
Kết quả
Nhập 5 chuỗi đầu vào: Sample text1 sample text2 hello how are you Welcome to tutorialspoint Good morning Chuỗi 0 bắt đầu bằng chữ hoa Chuỗi 3 bắt đầu bằng chữ hoa Chuỗi 4 bắt đầu bằng chữ hoa