使用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 给英雄的祝福语简短