如何使用Java RegEx匹配单词边界?
您可以使用元字符“\\b”来匹配单词边界。
例子1
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String args[]) {
//从用户读取字符串
System.out.println("Enter a String");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String regex = "\\b";
//编译正则表达式
Pattern pattern = Pattern.compile(regex);
//检索匹配器对象
Matcher matcher = pattern.matcher(input);
int count = 0;
while(matcher.find()) {
count++;
}
System.out.println("Number of word boundaries: "+count);
}
}输出结果
Enter a String this is a sample text Number of word boundaries: 10
例子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]";
//创建一个模式对象
Pattern pattern = Pattern.compile(regex);
//创建一个Matcher对象
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()+" ");
}
}
}输出结果
Enter sample text: National Intelligence Agency Research & Analysis Wing First letter of each word from the given string: N I A R A W