- 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
Extracting each word from a string using Regex in Java
A word represents continous letters from a to z or A to Z. Using Regex that matches any letter from a-z and A-Z will suffice the need. We'll use the following regex pattern −
[a-zA-Z]+
- [a-z] matches any character from a to z.
- [A-Z] matches any character from A to Z.
- + matches 1 or more characters from the group.
Example
import java.util.regex.Matcher; import java.util.regex.Pattern; public class Tester { public static void main(String[] args) { String candidate = "this is a test, A TEST."; String regex = "[a-zA-Z]+"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(candidate); System.out.println("INPUT: " + candidate); System.out.println("REGEX: " + regex + "\r
"); while (m.find()) { System.out.println(m.group()); } } }
This will produce the following result −
Output
this is a test A TEST
- Related Articles
- Getting first letter of each word in a String using regex in Java
- Print first letter of each word in a string using C# regex
- Java Program to Print first letter of each word using regex
- How to extract each (English) word from a string using regular expression in Java?
- How to match word characters using Java RegEx?
- How to match word boundaries using Java RegEx?
- How to match a non-word character using Java RegEx?
- How to match non-word boundaries using Java RegEx?
- How to extract an HTML tag from a String using regex in Java?
- Find frequency of each word in a string in Java
- C++ Program to Print first letter of each word using regex
- Golang program to print first letter of each word using regex
- Write a java program to reverse each word in string?
- Write a java program to tOGGLE each word in string?
- How to match a character from given string including case using Java regex?

Advertisements