使用正则表达式打印字符串中每个单词的首字母
给定一个字符串,提取其中每个单词的首字母。 “单词”被定义为字母字符的连续字符串,即任何大写或小写字符az 或AZ。
例子:
Input : Geeks for geeks
Output :Gfg
Input : United Kingdom
Output : UK
下面是提取每个单词首字母的正则表达式。它使用'/b'(边界匹配器之一)。请参阅如何编写正则表达式?学习它。
\b[a-zA-Z]
// Java program to demonstrate extracting first
// letter of each word using Regex
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test
{
public static void main(String[] args)
{
String s1 = "Geeks for Geeks";
String s2 = "A Computer Science Portal for Geeks";
Pattern p = Pattern.compile("\\b[a-zA-Z]");
Matcher m1 = p.matcher(s1);
Matcher m2 = p.matcher(s2);
System.out.println("First letter of each word from string \"" + s1 + "\" : ");
while (m1.find())
System.out.print(m1.group());
System.out.println();
System.out.println("First letter of each word from string \"" + s2 + "\" : ");
while (m2.find())
System.out.print(m2.group());
}
}
输出:
First letter of each word from string "Geeks for Geeks" :
GfG
First letter of each word from string "A Computer Science Portal for Geeks" :
ACSPfG
下一篇:在Java中使用 Regex 从字符串中提取每个单词