如何在字串中刪除所有除“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
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP