使用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 好听的元旦简短祝福语