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.
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 words from a given String
We have also discussed basic approach for java in these posts : Counting number of lines, words, characters and paragraphs in a text file using Java and Print first letter in word using Regex.
In this post, we will discuss Regular Expression approach for doing the same. This approach is best in terms of Time Complexity and is also used for large input files. Below is the regular expression for any word.
Words from string "Geeks for Geeks" : Geeks for Geeks Words from string "A Computer Science Portal for Geeks" : A Computer Science Portal for Geeks
This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.
Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.
- Get the first letter of each word in a string using regex in Java
- Print first letter of each word in a string using regex
- Check if a string contains only alphabets in Java using Regex
- Java | Date format validation using Regex
- Java | Removing whitespaces using Regex
- Count occurrences of a given character using Regex in Java
- Java program to count the characters in each word in a given sentence
- Extract maximum numeric value from a given string | Set 2 (Regex approach)
- How to validate an IP address using ReGex
- Regex Boundary Matchers in Java
- Java program to count the occurrence of each character in a string using Hashmap
- Length Of Last Word in a String
- Remove a given word from a String
- Check whether two Strings are Anagram of each other using HashMap in Java
- Retrieving Elements from Collection in Java (For-each, Iterator, ListIterator & EnumerationIterator)
- For-each loop in Java
- Java program to count the occurrences of each character
- String Literal Vs String Object in Java
- Insert a String into another String in Java
- Convert Set of String to Array of String in Java