রেগুলার এক্সপ্রেশন [a-zA-Z]+ এক বা একাধিক ইংরেজি অক্ষর ম্যাচ করে। তাই, দেওয়া ইনপুট স্ট্রিং থেকে প্রতিটি শব্দ বের করতে:
- উপরোক্ত এক্সপ্রেশনটি
Patternক্লাসেরcompile()মেথডে কম্পাইল করুন। Patternক্লাসেরmatcher()মেথডে ইনপুট স্ট্রিং পাস করেMatcherঅবজেক্ট পান।- শেষে, প্রতিটি ম্যাচের জন্য
group()মেথড কল করে মিলে যাওয়া ক্যারেক্টারগুলো পান।
উদাহরণ
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]+";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(data);
System.out.println("Words in the given String: ");
while(matcher.find()) {
System.out.println(matcher.group() + " ");
}
}
}
আউটপুট
Enter sample text: Hello this is a sample text Words in the given String: Hello this is a sample text