सबएक्सप्रेशन/मेटाकैरेक्टर “\s” व्हाइटस्पेस समकक्ष से मिलान करता है।
उदाहरण 1
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
public static void main( String args[] ) {
String regex = "\\s";
String input = "Hello 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);
}
}
आउटपुट
मिलान की संख्या: 7
उदाहरण 2
निम्नलिखित उदाहरण एक स्ट्रिंग पढ़ता है और उनके बीच के सभी अतिरिक्त स्पेस को हटा देता है।
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String args[]) {
// उपयोगकर्ता से स्ट्रिंग पढ़ना
System.out.println("एक स्ट्रिंग दर्ज करें");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
// स्पेस (एक या अधिक) से मिलान के लिए रेगुलर एक्सप्रेशन
String regex = "\\s+";
// रेगुलर एक्सप्रेशन संकलित करना
Pattern pattern = Pattern.compile(regex);
// Matcher ऑब्जेक्ट प्राप्त करना
Matcher matcher = pattern.matcher(input);
// सभी स्पेस कैरेक्टर को सिंगल स्पेस से बदलना
String result = matcher.replaceAll(" ");
System.out.print("अनावश्यक स्पेस हटाने के बाद टेक्स्ट: \n" + result);
}
}
आउटपुट
एक स्ट्रिंग दर्ज करें hello this is a sample text with irregular spaces अनावश्यक स्पेस हटाने के बाद टेक्स्ट: hello this is a sample text with irregular spaces