我正在尝试编写一个方法来检查字符串是否包含数字。如果是的话,只需要增加数量即可。
例如,如果位置为 1,则结果应为: “a12”->“a13” “a-b-c34”->“a-b-c35”
public static String incrementNumber(String number, int position){
Pattern pattern = Pattern.compile("\\\\d+");
Matcher matcher = pattern.matcher(number);
while (matcher.find()) {
for (int i = 1; i <= matcher.groupCount(); i++) {
String num = matcher.group();
int inc = Integer.parseInt(num)+position;
String incrementedString = String.format("%0" + num.length() + "d", inc);
number = matcher.replaceFirst(incrementedString);
}
}
return number;
}
目前,它根本没有增加。它不会进入 while 内部。 我无法判断我的正则表达式是否完全错误或者我错过了一个步骤。
这是一种方法。尽管这可以通过模式匹配和流来完成,但任务的开销和简单性表明这是一个必要的解决方案。完成这两件事后效率会更高。
这会迭代字符,并将字符附加到
StringBuilder
或动态解析一组数字,附加该数字 + 1。 boolean
用于控制整数解析和简单字符附加之间的当前状态.
如果源字符串以数字结尾,布尔值将指示循环结束后是否将计算值 + 1 添加到 StringBuilder。
StringBuilder sb = new StringBuilder();
boolean digitFound = false;
int value = 0;
for (char c : s.toCharArray()) {
// The following if/else block simply manages conversion
// of a series of digits to a number. When no is digit encountered,
// append the number and reset the value and flags.
if (Character.isDigit(c)) {
digitFound = true;
value = value * 10 + c -'0';
} else if (digitFound) {
sb.append(value+1);
value = 0;
digitFound = false;
}
// if not in midst of processing a number, add character to builder
if (!digitFound) {
sb.append(c);
}
}
// just in case the a number was at the end of the string.
if (digitFound) {
sb.append(value+1);
}
打印
23a-b-c35-a-b-c-d45-d23
这是使用流的一个示例。
String result = Arrays.stream(s.split("(?<=\\d)(?!\\d)|(?<=\\D)(?!\\D)"))
.map(token -> token.matches("\\d+")
? (Integer.parseInt(token) + 1) + ""
: token)
.collect(Collectors.joining());