जावा रेगुलर एक्सप्रेशन में \b मेटा कैरेक्टर शब्द सीमाओं (word boundaries) से मिलान करता है। इसलिए, दिए गए इनपुट टेक्स्ट से किसी विशेष शब्द को खोजने के लिए, आवश्यक शब्द को रेगुलर एक्सप्रेशन में शब्द सीमाओं के भीतर निर्दिष्ट करें:
"\\brequired word\\b"
उदाहरण 1
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MachingWordExample1 {
public static void main(String args[]) {
// स्ट्रिंग मान पढ़ना
Scanner sc = new Scanner(System.in);
System.out.println("इनपुट स्ट्रिंग दर्ज करें");
String input = sc.next();
// अंक खोजने के लिए रेगुलर एक्सप्रेशन
String regex = "\\bhello\\b";
// रेगुलर एक्सप्रेशन कंपाइल करना
Pattern pattern = Pattern.compile(regex);
// मैचर ऑब्जेक्ट प्राप्त करना
Matcher matcher = pattern.matcher(input);
if(matcher.find()) {
System.out.println("मिलान मिला");
} else {
System.out.println("मिलान नहीं मिला");
}
}
}
आउटपुट
इनपुट स्ट्रिंग दर्ज करें hello welcome to Tutorialspoint मिलान मिला
उदाहरण 2
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatcherExample2 {
public static void main(String args[]) {
String input = "This is sample text \n" + "This is second line " + "This is third line";
String regex = "\\bsecond\\b";
// रेगुलर एक्सप्रेशन कंपाइल करना
Pattern pattern = Pattern.compile(regex);
// मैचर ऑब्जेक्ट प्राप्त करना
Matcher matcher = pattern.matcher(input);
if(matcher.find()) {
System.out.println("मिलान मिला");
} else {
System.out.println("मिलान नहीं मिला");
}
}
}
आउटपुट
मिलान मिला