-1

我有以下字符串,我想根据spilts字符串中的最后一个字母来字符串,例如考虑

 String str =  '02191204E8DA4459.jpg' how to extract 4459 from str ? 

我尝试以下代码,但是在上面的字符串字母表中实际上并不是恒定的,我想在数据库中添加图像序列,例如

'02191204E8DA4459.jpg' to '02191204E8DA4465.jpg' i.e 6 images

  String sec1 = null, sec2 = null, result = null, initfilename = null;
    int lowerlimit, upperlimit;
    String realimg1, realimg2;
    String str1 = "120550DA121.jpg"; // here  DA is constant 
    String str2 = "120550DA130.jpg"; //
    String[] parts1;
    String[] parts2;
    realimg1 = str1.substring(0, str1.length() - 4); // remove .jpg from image name
    realimg2 = str2.substring(0, str2.length() - 4); //
    if (realimg1.matches(".*[a-zA-Z]+.*")) {             // checking whether imagename has alphabets 
        parts1 = realimg1.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)"); // It matches positions between a number and not-a-number (in any order).
        parts2 = realimg2.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)"); // It matches positions between a number and not-a-number (in any order).

        sec1 = parts1[0];
        sec2 = parts1[1];

        result = sec1.concat(sec2);

        lowerlimit = Integer.parseInt(parts1[parts1.length - 1]);
        upperlimit = Integer.parseInt(parts2[parts2.length - 1]);

        for (int j = lowerlimit; j <= upperlimit; j++) {
            initfilename = result + j + ".jpg";
            System.out.println(initfilename);
        }
    } else {
        for (int j = Integer.parseInt(realimg1); j <= Integer.parseInt(realimg2); j++) {
            initfilename = j + ".jpg";
            System.out.println(initfilename);
        }
    }
4

3 回答 3

1

您可以使用正则表达式:

String str =  "02191204E8DA4459.jpg";
if(str.matches(".*\\d{4}\\.jpg")) {
    System.out.println(str.replaceAll(".*(\\d{4})\\.jpg", "$1"));
}
  • str.matches(".*\\d{4}\\.jpg")true如果字符串以 4 位数字和 .jpg 结尾,则返回
  • str.replaceAll(".*(\\d{4})\\.jpg", "$1")返回一个包含您要查找的 4 位数字的新字符串

如果你不知道你会有多少位数,你可以用这个替换你的正则表达式:

.*(\\d+)\\.jpg
于 2013-10-01T13:15:10.337 回答
1

您可以拆分非数字并提取结果数组的最后一个元素:

String str = "02191204E8DA4459.jpg";

String[] split = str.split("\\D+");
System.out.println(split[split.length - 1]);
4459
于 2013-10-01T13:18:00.380 回答
1

也许不是最干净的方式,因为它不适用于前面没有非数字的字符串:

String str = "02191204E8DA4459.jpg";
String lastNumber = str.replaceAll("^.*[^0-9](\\d+).*?$", "$1");
System.out.println(lastNumber);
于 2013-10-01T13:31:06.593 回答