Java 程序如何删除字符串中除"1"和"2"之外的所有数字?

javaobject oriented programmingprogramming更新于 2025/2/12 2:52:17

  • 正则表达式"(?<!\d)digit(?!\d)"与指定的数字匹配。

  • replaceAll() 方法接受两个字符串:一个正则表达式模式和替换字符串,并用指定的字符串替换模式。

  • 因此,要删除字符串中除 1 和 2 之外的所有数字,请分别用一和二替换正则表达式 1 和 2,并用空字符串替换所有其他数字。

示例

import java.util.Scanner;
public class RegexExample {
   public static void main(String args[]) {
      //从用户读取字符串
      System.out.println("输入字符串");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      //匹配数字 1 的正则表达式
      String regex1 = "(?<!\d)1(?!\d)";
      //匹配数字 2 的正则表达式
      String regex2 = "(?<!\d)2(?!\d)";
      //将所有空格字符替换为单个空格
      String result = input.replaceAll(regex1, "one")
         .replaceAll(regex2, "two")
         .replaceAll("\s*\d+", "");
      System.out.print("Result: "+result);
   }
}

输出

输入字符串
sample 1 2 3 4 5 6
Result: sample one two

相关文章


有用资源