2013-10-01 94 views
-1

數字和字符的組合,我有以下字符串我要根據最後的字母字符串 爲如spilts字符串考慮如何找到字符串最後的字母是在java中

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

我嘗試下面的代碼但但在上面的字符串字母不恆定 actullally我想添加圖片sequeunce在數據庫如

'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); 
     } 
    } 
+1

你試過了什麼? – Thomas

+0

我相信如果你真的考慮過你的問題,你可以在沒有SO社區的幫助下解決它。只是至少嘗試一些東西.. –

+0

是的正確的我試圖解決,但我卡住了某處 –

回答

1

也許不是最乾淨的方式,因爲它不會對字符串的工作不被非前數字:

String str = "02191204E8DA4459.jpg"; 
String lastNumber = str.replaceAll("^.*[^0-9](\\d+).*?$", "$1"); 
System.out.println(lastNumber); 
+0

感謝回答,但如何找到第一部分,即02191204E8DA? –

+0

對於第一部分,請嘗試:「^(。* [^ 0-9])(\\ d +)。*?$」 –

+0

感謝您的幫助....... –

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 
+1

我想,最後不會總是有4個字母。 –

+0

@JoshM對,更新了答案,謝謝! – BackSlash

+0

@MCL是的,完全忘了逃脫點,我更新了答案,謝謝! – BackSlash

1

你可以拆分非數字和提取結果數組的最後一個元素:

String str = "02191204E8DA4459.jpg"; 

String[] split = str.split("\\D+"); 
System.out.println(split[split.length - 1]); 
 
4459 
相關問題