Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Finding all words that start with an 'a' in Java
All the words that start with a can be found in a string by using regular expressions in Java. The regular expressions are character sequences that can be used to match other strings using a specific pattern syntax. The regular expressions are available in the java.util.regex package which has many classes but the most important are Pattern class and Matcher class.
A program that finds all words that start with an 'a' is using regular expressions is given as follows:
Example
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Demo {
public static void main(String args[]) throws Exception {
String str = "This is an apple";
String regex = "\ba\w*\b";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(str);
String word = null;
System.out.println("The input string is: " + str);
System.out.println("The Regex is: " + regex + "\r\n");
System.out.println("The words that start with a in above string are:");
while (m.find()) {
word = m.group();
System.out.println(word);
}
if (word == null) {
System.out.println("There are no words that start with a");
}
}
}
Output
The input string is: This is an apple The Regex is: \ba\w*\b The words that start with a in above string are: an apple
Advertisements