如何在字串中刪除所有除“1”和“2”外的數字的 Java 程式?


  • 正則表示式“(?<!\d)digit(?!\d)”匹配指定的數字。

  • replaceAll() 方法接受兩個字串:一個正則表示式模式和一個替換字串,並將模式替換為指定字串。

  • 因此,若要刪除字串中除 1 和 2 之外的所有數字,請用 1 和 2 分別替換正則表示式 1 和 2,並將所有其他數字替換為空字串。

示例

 線上演示

import java.util.Scanner;
public class RegexExample {
   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 the digit 1
      String regex1 = "(?<!\d)1(?!\d)";
      //Regular expression to match the digit 2
      String regex2 = "(?<!\d)2(?!\d)";
      //Replacing all space characters with single space
      String result = input.replaceAll(regex1, "one")
         .replaceAll(regex2, "two")
         .replaceAll("\s*\d+", "");
      System.out.print("Result: "+result);
   }
}

輸出

Enter a String
sample 1 2 3 4 5 6
Result: sample one two

更新日期:2020 年 1 月 10 日

191 次瀏覽

開啟你的 職業生涯

透過完成培訓課程獲得認證

開始
廣告
© . All rights reserved.