使用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
热门推荐
10 新年门口花束祝福语简短
11 盘锦结婚祝福语大全简短
12 父母生日祝福语 简短独特
13 家庭恩爱祝福语简短英文
14 高考俄语祝福语大全简短
15 虎年祝福语 诗句唯美简短
16 生日婚礼祝福语简短精辟
17 虎年喝酒拜年祝福语简短
18 教师闺蜜祝福语简短