使用Java中的正则表达式获取字符串中每个单词的第一个字母
一个单词是连续的一系列字母字符。使用正则表达式,我们需要搜索边界字符在A到Z或a到z之间。请看以下情况-
Input: Hello World Output: H W Input: Welcome to world of Regex Output: W t w o R
我们将正则表达式用作“\\b[a-zA-Z]”,其中\\b表示边界匹配器。参见示例-
示例
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Tester {
public static void main(String[] args) {
String input1 = "Hello World";
String input2 = "Welcome to world of Regex";
Pattern p = Pattern.compile("\\b[a-zA-Z]");
Matcher m = p.matcher(input1);
System.out.println("Input: " + input1);
System.out.print("Output: ");
while (m.find()){
System.out.print(m.group() + " ");
}
System.out.println("\n");
m = p.matcher(input2);
System.out.println("Input: " + input2);
System.out.print("Output: ");
while (m.find()){
System.out.print(m.group() + " ");
}
System.out.println();
}
}输出结果
Input: Hello World Output: H W Input: Welcome to world of Regex Output: W t w o R