Java Matcher过度替换组

时间:2017-12-04 16:05:32

标签: java matcher

public class HexASCIITest {
public static void main(String[] args) throws DecoderException, UnsupportedEncodingException {

    String test = "src=\"test/__test/path/path2/AA_5F00_20140915_5F00_15_5F00_11_5F00_55_5F00_image_5F005F00_name.jpg\"";

    Pattern patternImages = Pattern.compile("src=\"[^\"]*?/__test/[^/]*?/[^/]*?/([^\"/]*?)\"");
    Matcher matcherImages = patternImages.matcher(test);

    while(matcherImages.find()) {
        String imageName = matcherImages.group(1);

        Pattern pattern = Pattern.compile("_((?:[01234567890ABCDEF]{4}){1,})_");            
        Matcher matcher = pattern.matcher(imageName);

        while(matcher.find()) {     
            byte[] bytes = Hex.decodeHex(matcher.group(1).toCharArray());       
            String imagePath = new String(bytes, "latin1");             
            imagePath = imagePath.replaceAll("\0", "");
            imageName = imageName.replaceFirst("_((?:[01234567890ABCDEF]{4}){1,})_", imagePath.trim());
        }           
        System.out.println(imageName);
    }   
}   
}

大家好,这是我的一个程序,实际上应该将十六进制代码转换为ASCII,但似乎我遇到了逻辑问题,有人可以帮我吗?

初始图像名称为:AA_5F00_20140915_5F00_15_5F00_11_5F00_55_5F00_image_5F005F00_name.jpg 完成所有替换后:AA_15_11_55__image_5F005F00_name.jpg

当20140915日期消失并且 5F005F00 仍然存在时,它不应该如何工作。谢谢你的帮助!

1 个答案:

答案 0 :(得分:0)

找到它 正则表达式应该是 - 模式模式= Pattern.compile("(([0123456789ABCDEF] {4}){1,} )");

然后 - > byte [] bytes = Hex.decodeHex(matcher.group(2).toCharArray());

最后更换 imageName = imageName.replaceFirst(matcher.group(1),imagePath.trim());