在 Java 中解釋正則表示式“s”元字元


子表示式/元字元“\s”匹配空等效項。

示例 1

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
   public static void main( String args[] ) {
      String regex = "\s";
      String input = "Hello how are you welcome to Tutorialspoint !";
      Pattern p = Pattern.compile(regex);
      Matcher m = p.matcher(input);
      int count = 0;
      while(m.find()) {
         count++;
      }
      System.out.println("Number of matches: "+count);
   }
}

輸出

Number of matches: 7

示例 2

以下示例讀取一個字串,並移除其中的所有多餘空格。

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
   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 spaces (one or more)
      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);
   }
}

輸出

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

更新於:2019 年 11 月 19 日

124 次瀏覽

啟動你的職業

透過完成課程獲得認證

入門
廣告
© . All rights reserved.