私はランダムな文字列を持っています"aaaaaaBccccCCCCd"
効果を得るためにグループのテキストを検索するmake regexが必要"a6B1c4C4d1"
。正規表現は"(\\D+)\\D*\\1"
のように見えますが、一文字が失われています。このサンプルではB
とd
です。Java Regex compress String
誰かが考えていると思いますか?
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Compress {
public static void main(String[] args) {
String text = "aaaaaaBccccCCCCd";
String regex = "(\\D+)\\D*\\1"; // or (.+).*\\1
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(text);
String result = new String();
while (matcher.find()) {
String letter = matcher.group().substring(0, 1);
String numberOfLetter = String.valueOf(matcher.group().length());
result = result + letter + numberOfLetter;
}
System.out.println(result);
}
}
ありがとうございます。
なぜ '\ D'ですか?非数字のみをターゲティングしていますか? –
はい、数字以外は –