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
Live Demo
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