如何在字符串中删除所有除“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