Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment digit value in String

Tags:

java

regex

So, i have some String with digits and another symbols, and i want to increment the value of each digit at 1. For example: "test1check2" from this String i want to recieve "test2check3". And can i make this only with method "replaceAll"? (i.replaceAll("\d", ...) something like that)?, without to use methods such like indexOf, charAt...

like image 431
Le_Coeur Avatar asked Dec 22 '22 08:12

Le_Coeur


1 Answers

I don't think you can do it with a simple replaceAll(...), you'll have to write a few lines like:

Pattern digitPattern = Pattern.compile("(\\d)"); // EDIT: Increment each digit.

Matcher matcher = digitPattern.matcher("test1check2");
StringBuffer result = new StringBuffer();
while (matcher.find())
{
    matcher.appendReplacement(result, String.valueOf(Integer.parseInt(matcher.group(1)) + 1));
}
matcher.appendTail(result);
return result.toString();

There's probably some syntax errors here, but it will work something like that.

EDIT: You commented that each digit must be incremented separately (abc12d -> abc23d) so the pattern should be changed from (\\d+) to (\\d)

EDIT 2: Change StringBuilder to StringBuffer as required by Matcher class.

like image 97
Adrian Pronk Avatar answered Jan 03 '23 04:01

Adrian Pronk