English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
الرموز النمطية"\\s"التطابق مع المسافات، + تعني أن المسافة تظهر مرة واحدة أو أكثر، لذا العبارة النمطية \\ S + تتطابق مع جميع حروف المسافات (فراغ واحد أو أكثر). لذا يتم استبدال المسافات المتعددة بمسافة واحدة.
استبدال النص المدخل بالعبارات النمطية المذكورة أعلاه، ثم استبدال النتيجة بمسافة واحدة " ".
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ReplaceAllExample { public static void main(String args[]) { //read a string from the user System.out.println("Enter a String"); Scanner sc = new Scanner(System.in); String input = sc.nextLine(); String regex = "\\s+"; //compile the regular expression Pattern pattern = Pattern.compile(regex); //retrieve the matcher object Matcher matcher = pattern.matcher(input); //replace all space characters with a single space String result = matcher.replaceAll(" "); System.out.print("Text after removing unwanted spaces: \n"+result); } }
output 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
import java.util.Scanner; public class Test { public static void main(String args[]) { //read a string from the user System.out.println("Enter a String"); Scanner sc = new Scanner(System.in); String input = sc.nextLine(); //regular expression to match spaces String regex = "\\s+"; //replace the pattern with a single space String result = input.replaceAll(regex, " "); System.out.print("Text after removing unwanted spaces: \n"+result); } }
output 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