Bạn có thể so khớp các ranh giới từ bằng cách sử dụng ký tự meta “\\ 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[]) { //Reading String from user System.out.println("Enter a String"); Scanner sc = new Scanner(System.in); String input = sc.nextLine(); String regex = "\\b"; //Compiling the regular expression Pattern pattern = Pattern.compile(regex); //Retrieving the matcher object Matcher matcher = pattern.matcher(input); int count = 0; while(matcher.find()) { count++; } System.out.println("Number of word boundaries: "+count); } }
Đầu ra
Enter a String this is a sample text Number of word boundaries: 10
Ví dụ 2
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class FirstLetterExample { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter sample text: "); String data = sc.nextLine(); String regex = "\\b[a-zA-Z]"; //Creating a pattern object Pattern pattern = Pattern.compile(regex); //Creating a Matcher object Matcher matcher = pattern.matcher(data); System.out.println("First letter of each word from the given string: "); while(matcher.find()) { System.out.print(matcher.group()+" "); } } }
Đầu ra
Enter sample text: National Intelligence Agency Research & Analysis Wing First letter of each word from the given string: N I A R A W