使用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 妈妈生日祝福语简短励志