Dynamically increase all numbers within a string

Is there any Java solution replacing a digit in String other than getting a digit using a match, increment it by one, and replace?

"REPEAT_FOR_4" will return "REPEAT_FOR_5" "REPEAT_FOR_10" will return "REPEAT_FOR_11"

I would like to do this on a single line with a regular expression and replace, rather than by re-arranging the line as "REPEAT_FOR_" and add a number after the increment. Thank!

Further editing: I would like to know how to replace the number with the next line in the line.

+4
source share
3 answers

regex, . , .

public String getIncrementedString (String str){
return ("REPEAT_FOR_" + (Character.getNumericValue(str.charAt(11))+1));
}
0

.

String ss = "REPEAT_FOR_4";
int vd = Integer.valueOf(ss.substring(ss.length() - 1));
String nss = ss.replaceAll("\\d",String.valueOf(vd+1));

System.out.println(nss);

:

REPEAT_FOR_5

: .

    String ss = "REPEAT_5_FOR_ME";
    Pattern p = Pattern.compile("\\d+");
    Matcher m = p.matcher(ss);
    m.find();
    String strb = m.group();
    int vd = Integer.valueOf(strb);
    String nss = ss.replaceAll("\\d",String.valueOf(vd+1));

    System.out.println(nss);

:

REPEAT_6_FOR_ME

, , , .

public static String convStr(String str){
    Pattern p = Pattern.compile("\\d+");
    Matcher m = p.matcher(str);
    m.find();
    String strb = m.group();
    int vd = Integer.valueOf(strb);
    return str.replaceAll("\\d",String.valueOf(vd+1));
  }
0

Yes, of course, it is possible. using regex Patternand Matcher, here is what you need to do:

    String str = "REPEAT_FOR_4";
    Pattern p = Pattern.compile("([0-9]+)");
    Matcher m = p.matcher(str);
    StringBuffer s = new StringBuffer();
    while (m.find())
        m.appendReplacement(s, String.valueOf(1+ Integer.parseInt(m.group(1))));
    String updated = s.toString();
    System.out.println(updated);

This is a working example that returns REPEAT_FOR_5as output.

0
source

Source: https://habr.com/ru/post/1657628/


All Articles