Search code examples
javaregex

Replace All numeric substring with character


I have to replace all digit patterns with some character. For 1 digit its working fine for e.g for given string ramesh_gone_to_avbp_9_vc.pdf its working fine changing it to ramesh_gone_to_avbp_*_vc.pdf but for given input ramesh_gone_to_avbp_91_vc.pdf its changing to ramesh_gone_to_avbp_**_vc.pdf but i want output like ramesh_gone_to_avbp_*_vc.pdf

This is what i tried so far

String ss = "ramesh_gone_to_avbp_92_vc.pdf";
System.out.println(ss.replaceAll("(?<=[\\d\\.])-(?=[\\d\\.])", "*"));

Solution

  • You may simply match on \d+, which matches groups of numbers of one or more digits:

    String ss = "ramesh_gone_to_avbp_92_vc.pdf";
    String output = ss.replaceAll("\\d+", "*");
    System.out.println(output);  // ramesh_gone_to_avbp_*_vc.pdf