- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Getting first letter of each word in a String using regex in Java
A word is contiguous series of alphabetic characters. Using regex, we need to search the boundary character to be between A to Z or a to z. Consider the following cases −
Input: Hello World Output: H W Input: Welcome to world of Regex Output: W t w o R
We'll use the regex as "\b[a-zA-Z]" where \b signifies the boundary matchers. See the example −
Example
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("
"); m = p.matcher(input2); System.out.println("Input: " + input2); System.out.print("Output: "); while (m.find()){ System.out.print(m.group() + " "); } System.out.println(); } }
Output
Input: Hello World Output: H W Input: Welcome to world of Regex Output: W t w o R
- Related Articles
- Print first letter of each word in a string using C# regex
- Java Program to Print first letter of each word using regex
- Golang program to print first letter of each word using regex
- C++ Program to Print first letter of each word using regex
- Extracting each word from a string using Regex in Java
- Print first letter of each word in a string in C#
- How to capitalize the first letter of each word in a string using JavaScript?
- How to get first letter of each word using regular expression in Java?
- Capitalize last letter and Lowercase first letter of a word in Java
- Capitalizing first letter of each word JavaScript
- Return String by capitalizing first letter of each word and rest in lower case with JavaScript?
- Java Program to Capitalize the first character of each word in a String
- How to print the first character of each word in a String in Java?
- Find frequency of each word in a string in Java
- Python program to capitalize each word's first letter

Advertisements