The Wayback Machine - https://web.archive.org/web/20240826020941/https://www.geeksforgeeks.org/print-first-letter-word-string-using-regex/
Open In App

Print first letter of each word in a string using regex

Last Updated : 10 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a string, extract the first letter of each word in it. “Words” are defined as contiguous strings of alphabetic characters i.e. any upper or lower case characters a-z or A-Z. Examples:

Input : Geeks for geeks
Output :Gfg

Input : United Kingdom
Output : UK

Below is the Regular expression to extract the first letter of each word. It uses ‘/b'(one of boundary matchers). Please refer How to write Regular Expressions? to learn it.

\b[a-zA-Z]

Java




// 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());
         
         
    }
}


C#




// C# program to demonstrate extracting first
// letter of each word using Regex
 
using System;
using System.Text.RegularExpressions;
 
public class GFG
{
    public static void Main()
    {
        string s1 = "Geeks for Geeks";
        string s2 = "A Computer Science Portal for Geeks";
         
        Regex p = new Regex("\\b[a-zA-Z]");
         
         
        Console.WriteLine("First letter of each word from string \"" + s1 + "\" : ");
        foreach (Match ItemMatch in p.Matches(s1))
            Console.Write(ItemMatch.Value);
         
        Console.WriteLine();
         
        Console.WriteLine("First letter of each word from string \"" + s2 + "\" : ");
         
        foreach (Match ItemMatch in p.Matches(s2))
            Console.Write(ItemMatch.Value);
         
    }
}
 
// This code is contributed by Utkarsh


Python3




# Python program to demonstrate extracting first
# letter of each word using Regex
import re
 
s1="Geeks for Geeks"
s2="A Computer Science Portal for Geeks"
 
p = re.compile("\\b[a-zA-Z]")
 
print("First letter of each word from string '{0}' : ".format(s1))
 
for m1 in re.finditer(p,s1):
    print(m1.group(0),end="")
     
print()
 
print("First letter of each word from string '{0}' : ".format(s2))
 
for m2 in re.finditer(p,s2):
    print(m2.group(0),end="")
     
 
# This code is contributed by Pushpesh Raj.


Output:

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

Next Article: Extracting each word from a String using Regex in Java If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



Previous Article
Next Article

Similar Reads

Get the first letter of each word in a string using regex in Java
Given a string, extract the first letter of each word in it. "Words" are defined as contiguous strings of alphabetic characters i.e. any upper or lower case characters a-z or A-Z. Examples: Input : Geeks for geeks Output :Gfg Input : United Kingdom Output : UK Below is the Regular expression to extract the first letter of each word. It uses '/b'(on
1 min read
Extracting each word from a String using Regex in Java
Given a string, extract words from it. "Words" are defined as contiguous strings of alphabetic characters i.e. any upper or lower case characters a-z or A-Z. Examples: Input : Funny?? are not you? Output : Funny are not you Input : Geeks for geeks?? Output : Geeks for geeks We have discussed a solution for C++ in this post : Program to extract word
2 min read
Check if a String Contains only Alphabets in Java using Regex
Regular Expressions or Regex is an API for defining String patterns that can be used for searching, manipulating, and editing a text. It is widely used to define a constraint on strings such as a password. Regular Expressions are provided under java.util.regex package. For any string, here the task is to check whether a string contains only alphabe
2 min read
Program to check the validity of password without using regex.
Password checker program basically checks if a password is valid or not based on the password policies mention below: Password should not contain any space. Password should contain at least one digit(0-9). Password length should be between 8 to 15 characters. Password should contain at least one lowercase letter(a-z). Password should contain at lea
9 min read
How to validate an IP address using ReGex
Given an IP address, the task is to validate this IP address with the help of Regex (Regular Expression) in C++ as a valid IPv4 address or IPv6 address. If the IP address is not valid then print an invalid IP address. Examples: Input: str = "203.120.223.13" Output: Valid IPv4 Input: str = "000.12.234.23.23" Output: Invalid IP Input: str = "2F33:12a
5 min read
How to Validate SWIFT/BIC Code Using RegEx?
A SWIFT/BIC code consists of 8-11 characters SWIFT follows a format that identifies your bank, country, location, and branch. A SWIFT code — is also called a BIC number.BIC is a standard format for Business Identifier Codes (BIC). It’s used to identify banks and financial institutions globally. These codes are used when transferring money between b
7 min read
Metacharacters in Java Regex
Regex stands for Regular Expression, which is used to define a pattern for a string. It is used to find the text or to edit the text. Java Regex classes are present in java.util.regex package, which needs to be imported before using any of the methods of regex classes. java.util.regex package consists of 3 classes: PatternMatcherPatternSyntaxExcept
5 min read
Regex Character Cases in Java
Regular expressions (also called "Regex") are special types of pattern-matching strings that describe a pattern in a text. A regex can be matched against another string to see whether the string fits the pattern. In general, regex consists of normal characters, character classes, wildcard characters, and quantifiers. We will talk specifically about
6 min read
WireMock - URL Matching with Regex
WireMock is a tool for mocking HTTP-based APIs that runs in the unit tests, on the desktop, or in the test environment. Read more about WireMock in the article Introduction to WireMock. In this article, we are going to discuss one of the important concepts in Wiremock, i.e how to match the URL with Regex. Regex Matching on the URL Path Only JSON Ma
4 min read
Regex Boundary Matchers in Java
Prerequisite- Regular Expressions in Java Boundary matches can help us find where in the string match is taking place. You can make your pattern matches more precise by specifying such information with boundary matchers. For example, maybe you're interested in finding a particular word, but only if it appears at the beginning or end of a line. Or m
6 min read
How to use Regex in TestNG?
In this article, we will see how to use Regex in TestNG. In TestNG, we can use Regular Expressions for two purposes: To Include Test CasesTo Exclude Test Cases To include test cases we use the include the keyword in the testng.xml configuration file.To Exclude test cases we use the exclude keyword in the testng.xml configuration file.Table of Conte
5 min read
Length Of Last Word in a String
Given a string s consisting of upper/lower-case alphabets and empty space characters ' ', return the length of the last word in the string. If the last word does not exist, return 0. Examples: Input : str = "Geeks For Geeks"Output : 5length(Geeks)= 5Input : str = "Start Coding Here"Output : 4length(Here) = 4Input : **Output : 0Recommended PracticeL
14 min read
Print number of words, vowels and frequency of each character
Given a string str with uppercase, lowercase and special characters. The input string is to end with either a space or a dot. The problem is to calculate the number of words, vowels and frequency of each character of the string in a separate line. Example : Input : How Good GOD Is. Output : Number of words = 4 Number of vowels = 5 Number of upper c
8 min read
Print all possible paths from the first row to the last row in a 2D array
Given a 2D array of characters with M rows and N columns. The task is to print all the possible paths from top (first row) to bottom (last row). Examples: Input: arr[][] = { {'a', 'b', 'c'}, {'d', 'e', 'f'}, {'g', 'h', 'i'}} Output: adg adh adi aeg aeh aei afg afh afi bdg bdh bdi beg beh bei bfg bfh bfi cdg cdh cdi ceg ceh cei cfg cfh cfiInput: arr
7 min read
Apache Kafka Streams - Simple Word Count Example
Kafka Streams is used to create apps and microservices with input and output data stored in an Apache Kafka cluster. It combines the advantages of Kafka's server-side cluster technology with the ease of creating and deploying regular Java and Scala apps on the client side. Approach In this article, we are going to use Kafka streams for counting wor
5 min read
Swap the first and last character of a string in Java
Given string str, the task is to write a Java program to swap the first and the last character of the given string and print the modified string. Examples: Input: str = "GeeksForGeeks"Output: seeksForGeekGExplanation: The first character of the given string is 'G' and the last character of the given string is 's'. We swap the character 'G and 's' a
4 min read
Check whether two Strings are Anagram of each other using HashMap in Java
Write a function to check whether two given strings are an Anagram of each other or not. An anagram of a string is another string that contains the same characters, only the order of characters can be different. For example, "abcd" and "dabc" are an Anagram of each other. Approach: Hashmaps can be used to determine if two given strings are anagrams
3 min read
PrintWriter print(String) method in Java with Examples
The print(String) method of PrintWriter Class in Java is used to print the specified String value on the stream. This String value is taken as a parameter. Syntax: public void print(String StringValue) Parameters: This method accepts a mandatory parameter StringValue which is the String value to be written on the stream. Return Value: This method d
2 min read
PrintStream print(String) method in Java with Examples
The print(String) method of PrintStream Class in Java is used to print the specified String value on the stream. This String value is taken as a parameter. Syntax: public void print(String StringValue) Parameters: This method accepts a mandatory parameter StringValue which is the String value to be written on the stream. Return Value: This method d
2 min read
Print the middle character of a string
Given string str, the task is to print the middle character of a string. If the length of the string is even, then there would be two middle characters, we need to print the second middle character. Examples: Input: str = "Java"Output: vExplanation: The length of the given string is even. Therefore, there would be two middle characters 'a' and 'v',
3 min read
Print all Subsequences of String which Start with Vowel and End with Consonant.
Given a string return all possible subsequences which start with a vowel and end with a consonant. A String is a subsequence of a given String, that is generated by deleting some character of a given string without changing its order. Examples: Input : 'abc'Output : ab, ac, abcInput : 'aab'Output : ab, aabQuestion Source: Yatra.com Interview Experi
13 min read
Print all unique words of a String
Write a function that takes a String as an argument and prints all unique words in it. Examples: Input: Java is great. Grails is also greatOutput: Java Grails also Approach: The idea is to use the map to keep track of words already occurred. But first, we have to extract all words from a String, as a string may contain many sentences with punctuati
7 min read
Print all subsequences of a string
Given a string, we have to find out all its subsequences of it. A String is a subsequence of a given String, that is generated by deleting some character of a given string without changing its order. Examples:  Input : abcOutput : a, b, c, ab, bc, ac, abc Input : aaaOutput : a, a, a, aa, aa, aa, aaa Method 1 (Pick and Don't Pick Concept) : Implemen
15+ min read
Creating First Servlet Application using NetBeans IDE
Servlets are the Java programs that run on the Java-enabled web server or application server. They are used to handle the request obtained from the webserver, process the request, produce the response, then send a response back to the webserver. NetBeans is an integrated development environment (IDE) for Java. NetBeans allows applications to be dev
2 min read
Print characters and their frequencies in order of occurrence using a LinkedHashMap in Java
Given a string str containing only lowercase characters. The task is to print the characters along with their frequencies in the order of their occurrence in the given string.Examples: Input: str = "geeksforgeeks" Output: g2 e4 k2 s2 f1 o1 r1Input: str = "helloworld" Output: h1 e1 l3 o2 w1 r1 d1 Approach: Traverse the given string character by char
2 min read
Print Hello World Without using a Semicolon in Java
Every statement in Java must end with a semicolon as per the basics. However, unlike other languages, almost all statements in Java can be treated as expressions. However, there are a few scenarios when we can write a running program without semicolons. If we place the statement inside an if/for statement with a blank pair of parentheses, we don’t
2 min read
Modify a Circular Doubly Linked List such that each node stores the sum of all nodes except itself
Given a circular doubly linked list consisting of N nodes, the task is to modify every node of the given Linked List such that each node contains the sum of all nodes except that node. Examples: Input: 4 ↔ 5 ↔ 6 ↔7 ↔ 8Output: 26 ↔ 25 ↔ 24 ↔ 23 ↔ 22Explanation:1st Node: Sum of all nodes except itself = (5 + 6 + 7 + 8) = 26.2nd Node: Sum of all nodes
15+ min read
Sum of leaf nodes at each horizontal level in a binary tree
Given a Binary Tree, the task is to find the sum of leaf nodes at every level of the given tree. Examples: Input: Output:0063012Explanation:Level 1: No leaf node, so sum = 0Level 2: No leaf node, so sum = 0Level 3: One leaf node: 6, so sum = 6 Level 4: Three leaf nodes: 9, 10, 11, so sum = 30Level 5: One leaf node: 12, so sum = 12 Input: Output:006
14 min read
Generate an Array by multiplying each element of given Array by K
Given an array arr[] of size N and an integer K. The task is to multiply each element of the array by K. Examples : Input: arr[] = { 3, 4 }, K = 2Output: 6 8Explanation: The elements become 3*2 = 6 and 4*2 = 8. Input: arr[] = { 0, 1, 2 }, K = 7Output: { 0, 7, 14 } Approach: The given problem can be solved using the following steps : Iterate through
6 min read
How Eureka Server and Client Communicate with Each Other in Microservices?
Service Discovery is one of the major things of a microservice-based architecture. Eureka is the Netflix Service Discovery Server and Client. The server can be configured and deployed to be highly functional, with each server copying the state of the registered services to the others. In the previous article, we have seen How to Register Microservi
5 min read