如何使用 Java 正則表示式用單個空格替換字串中的多個空格?


元字元 “\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[]) {
      //Reading String from user
      System.out.println("Enter a String");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      String regex = "\s+";
      //Compiling the regular expression
      Pattern pattern = Pattern.compile(regex);
      //Retrieving the matcher object
      Matcher matcher = pattern.matcher(input);
      //Replacing all space characters with single space
      String result = matcher.replaceAll(" ");
      System.out.print("Text after removing unwanted spaces: \n"+result);
   }
}

Maruthi Krishna

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[]) {
      //Reading String from user
      System.out.println("Enter a String");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      //Regular expression to match space(s)
      String regex = "\s+";
      //Replacing the pattern with single space
      String result = input.replaceAll(regex, " ");
      System.out.print("Text after removing unwanted spaces: \n"+result);
   }
}

Maruthi Krishna

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

Maruthi Krishna

開啟你的職業生涯

完成課程,獲得認證

開始
廣告
© . All rights reserved.