English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Regular expression “ [a-zA-Z] + ”Matching one or more English letters. Therefore, to extract each word from the given input string-
Compilecompile()
The above expression of the methods in the Pattern class.
bypass the required input string asmatcher()
the method of the Pattern class as the parameter to get the Matcher object.
Finally, for each match, callgroup()
method to get the matched characters.
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class EachWordExample { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter sample text:"); String data = sc.nextLine(); String regex = "[a-zA-Z]+"; //Create a pattern object Pattern pattern = Pattern.compile(regex); //Create a Matcher object Matcher matcher = pattern.matcher(data); System.out.println("Words in the given String:"); while(matcher.find()) { System.out.println(matcher.group())+""); } } }
Output Result
Enter sample text: Hello this is a sample text Words in the given String: Hello this is a sample text