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
热门推荐
10 晚来的生日祝福语简短
11 古风祝福语 唯美简短结婚
12 自由 生日祝福语简短独特
13 工资涨高祝福语简短
14 火把节祝福语简短
15 谢谢同事英文祝福语简短
16 祝福语闺蜜简短单纯
17 业主装修完成祝福语简短
18 妈妈病人出院祝福语简短