সাবএক্সপ্রেশন/মেটাক্যারেক্টার "^" লাইনের শুরু ম্যাচ করে। রেগুলার এক্সপ্রেশনে ব্যবহার করলে, এটি ইনপুট স্ট্রিংয়ের শুরুতে 오는 অংশ ম্যাচ করে।
উদাহরণ ১: "Hi how are you" দিয়ে শুরু
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
public static void main(String args[]) {
String regex = "^Hi how are you";
String input = "Hi how are you welcome to Tutorialspoint";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
int count = 0;
while (m.find()) {
count++;
}
System.out.println("ম্যাচের সংখ্যা: " + count);
}
}
আউটপুট
ম্যাচের সংখ্যা: 1
উদাহরণ ২: ডিজিট দিয়ে শুরু হওয়া স্ট্রিং খুঁজা
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StartingwithDigit {
public static void main(String args[]) {
String regex = "^[0-9].*$";
Scanner sc = new Scanner(System.in);
System.out.println("৫টি ইনপুট স্ট্রিং দিন: ");
String input[] = new String[5];
for (int i = 0; i < 5; i++) {
input[i] = sc.nextLine();
}
Pattern p = Pattern.compile(regex);
System.out.println("ডিজিট দিয়ে শুরু হওয়া স্ট্রিংগুলো: ");
for (int i = 0; i < 5; i++) {
Matcher m = p.matcher(input[i]);
if (m.matches()) {
System.out.println(m.group());
}
}
}
}
আউটপুট
৫টি ইনপুট স্ট্রিং দিন: sample string 1 sample string 2 11 sample string 3 22 sample string 4 43534 56353 636 ডিজিট দিয়ে শুরু হওয়া স্ট্রিংগুলো: 11 sample string 3 22 sample string 4 43534 56353 636
নোট: ^ ডিফল্টে স্ট্রিংয়ের শুরু। Pattern.MULTILINE ফ্ল্যাগ থাকলে প্রতিটি লাইনের শুরুতে ম্যাচ করে। \\A সবসময় স্ট্রিংয়ের আসলো৫ শুরু ম্যাচ করে।