元字符“ \ b ”匹配单词边界,[a-zA-Z]匹配英语字母中的一个字符(两种情况)。简而言之,表达式\ \ b [a-zA-Z]匹配英语字母中的单个字符,这两种情况均在每个单词边界之后。
因此,要检索每个单词的首字母-编译compile()Pattern类的方法的以上表达式。
绕过所需的输入字符串作为matcher()Pattern类的方法的参数,获取Matcher对象。
最后,对于每个匹配项,通过调用group()方法获得匹配的字符。
示例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