我正在使用RLE,我正在尝试用Java创建一个解压缩程序。我有:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Scanner;
public class Decompress {
public static String decode(String string) {
StringBuffer dest = new StringBuffer();
Pattern pattern = Pattern.compile("[0-9]+|[a-zA-Z]");
Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
int number = Integer.parseInt(matcher.group());
matcher.find();
while (number-- != 0) {
dest.append(matcher.group());
}
}
return dest.toString();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter string: ");
String string = sc.nextLine();
String output = "";
System.out.println(decode(output));
}
}
但它对我不起作用。我有用户输入,如a2b3和输出aabbb,它不能硬编码
答案 0 :(得分:0)
你应该做([a-zA-Z])([0-9]+)
作为正则表达式。这样你就可以使用正则表达式解析部分了。
Pattern pattern = Pattern.compile("([a-zA-Z])(\d+)");
Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
String letter = matcher.group();
int number = Integer.parseInt(matcher.group());
while (number-- != 0) {
dest.append(letter);
}
matcher.find();
}