Java程序要删除字符串中除“ 1”和“ 2”以外的所有数字?
正则表达式“(?<!\\d)digit(?!\\d)”与指定的数字匹配。
replaceAll()方法接受两个字符串:正则表达式模式和替换字符串,并将模式替换为指定的字符串。
因此,要删除字符串中除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
热门推荐
1 训练狗狗工作
4 狗狗定点排便训练
5 狗狗训练吠叫
6 狗狗尿垫训练
7 狗狗训练座
8 狗狗训练攻略
9 狗狗训练记
10 做训练狗狗
11 狗狗训练词
12 狗狗谢谢怎么训练
13 狗狗训练如厕
14 狗狗太凶怎么训练
15 狗狗训练它
16 狗狗克制训练
17 训练基地狗狗
18 怎么样训练狗狗大小硬