正则表达式“ (?<!\\ 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