English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Wie ersetzt man mehrere Leerzeichen in einer Zeichenkette durch ein einzelnes Leerzeichen mit Java-RegEx?

Meta-Zeichen"\\s"Mit Leerzeichen abgestimmt,+Stellt die einmalige oder mehrfache Erscheinung eines Leerzeichens dar, daher der reguläre Ausdruck \\ S +Mit allen Leerzeichenzeichen (einzelne oder mehrere) abgestimmt. Daher wird ein Leerzeichen durch mehrere Leerzeichen ersetzt.

Das Eingabezeichen wird mit dem obigen regulären Ausdruck abgeglichen und das Ergebnis wird durch einen einzigen Leerzeichen "" ersetzt.

例子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 = 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
Vielleicht gefällt Ihnen auch