我想了解 Java 中此 Ruby 代码的等效内容:
str.gsub(/(.)\1*/) do
"#{$&.size}#{$1}"
end
它的作用是用重复次数和字符本身替换相同连续字符的出现。 例如:“111”会变成“31”,因为有三个一,“111223”会变成“312213”,因为有三个一,两个二,一个三等等。它基本上被称为“look-and” -说”数字。我想使用正则表达式来完成此操作,可能没有任何循环。
最佳答案
那么,您可以使用基于 Matcher#appendReplacement
的代码:
String s = "111";
StringBuffer result = new StringBuffer();
Matcher m = Pattern.compile("(.)\\1+").matcher(s);
while (m.find()) {
m.appendReplacement(result, m.group().length() + m.group(1));
}
m.appendTail(result);
System.out.println(result.toString()); // => 31
请参阅IDEONE demo
关于java - 将出现次数替换为其编号(将数字视为 Java 中的正则表达式),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34203395/