Computer >> Máy Tính >  >> Lập trình >> Java

Làm cách nào để thay thế nhiều khoảng trắng trong một chuỗi bằng cách sử dụng một khoảng trắng duy nhất bằng cách sử dụng Java regex?

Siêu ký tự “\\ s” khớp với khoảng trắng và + cho biết sự xuất hiện của khoảng trắng một hoặc nhiều lần, do đó, biểu thức chính quy \\ S + khớp với tất cả các ký tự khoảng trắng (đơn hoặc nhiều). Do đó, để thay thế nhiều dấu cách bằng một dấu cách.

Khớp chuỗi đầu vào với biểu thức chính quy ở trên và thay thế kết quả bằng một khoảng trắng “”.

Ví dụ 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);
   }
}

Đầu ra

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

Ví dụ 2

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);
   }
}

Đầu ra

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