Bạn có thể khớp ranh giới không phải từ bằng metaký tự “\\B”.
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 = "\\B";
// 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);
int count = 0;
while (matcher.find()) {
count++;
}
System.out.println("Số ranh giới không phải từ: " + count);
}
}
Kết quả
Nhập một chuỗi this is a sample text Số ranh giới không phải từ: 12
Ví dụ 2
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String args[]) {
String regex = "\\Bin";
Scanner sc = new Scanner(System.in);
System.out.println("Nhập một chuỗi: ");
String input = sc.nextLine();
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
int count = 0;
while (m.find()) {
count++;
}
System.out.println("số ranh giới không phải từ: " + count);
}
}
Kết quả
Nhập một chuỗi: this is a sample text in win tin pin sin số ranh giới không phải từ: 4