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