簡體   English   中英

在某個字符的最后一次出現處拆分字符串

[英]Split string on the last occurrence of some character

我基本上是在嘗試在最后一個時期拆分一個字符串來捕獲文件擴展名。 有時該文件沒有任何擴展名,所以我很期待。

但問題是某些文件名在結尾之前有句點,就像這樣......

/mnt/sdcard/OG Ron C, Chopstars & Drake - Choppin Ain't The Same-2013-MIXFIEND/02 Drake - Connect (Feat. Fat Pat) (Chopped Not Slopped).mp3

因此,當該字符串出現時,它會在“02 Drake - Connect (Feat.”) 處截斷它。

這是我一直在使用的...

String filePath = intent.getStringExtra(ARG_FILE_PATH);
String fileType = filePath.substring(filePath.length() - 4);
String FileExt = null;
try {
    StringTokenizer tokens = new StringTokenizer(filePath, ".");
    String first = tokens.nextToken();
    FileExt = tokens.nextToken();
}
catch(NoSuchElementException e) {
    customToast("the scene you chose, has no extension :(");
}
System.out.println("EXT " + FileExt);
File fileToUpload = new File(filePath);

如何在文件擴展名處拆分字符串,但在文件沒有擴展名時也能夠處理和警告。

你可以試試這個

int i = s.lastIndexOf(c);
String[] a =  {s.substring(0, i), s.substring(i)};

假設以點結尾並后跟字母數字字符的文件具有擴展名可能更容易。

int p=filePath.lastIndexOf(".");
String e=filePath.substring(p+1);
if( p==-1 || !e.matches("\\w+") ){/* file has no extension */}
else{ /* file has extension e */ }

有關正則表達式模式,請參閱Java 文檔 記住要轉義反斜杠,因為模式字符串需要反斜杠。

這是Java嗎? 如果是這樣,為什么不使用“java.io.File.getName”。

例如:

File f = new File("/aaa/bbb/ccc.txt");
System.out.println(f.getName());

出去:

ccc.txt

您可以在您的正則表達式中使用積極的前瞻來確保它只在最后一次出現時拆分。 正向前瞻確保它僅在字符串中稍后沒有出現另一個事件時才拆分。

// Using example filePath from question
String filePath = "/mnt/sdcard/OG Ron C, Chopstars & Drake - Choppin Ain't The Same-2013-MIXFIEND/02 Drake - Connect (Feat. Fat Pat) (Chopped Not Slopped).mp3";
String[] parts = filePath.split("\\.(?=[^.]*$)");
// parts = [
//     "/mnt/sdcard/OG Ron C, Chopstars & Drake - Choppin Ain't The Same-2013-MIXFIEND/02 Drake - Connect (Feat. Fat Pat) (Chopped Not Slopped)"
//     "mp3"
// ]

分解正則表達式:

  • \\. - 找到一個時期
  • (?=[^.]*$) - 確保之后的所有內容都不是句點,而不包括在匹配中)

如何使用句點作為分隔符拆分 filPath。 並獲取該數組中的最后一項以獲取擴展名:

        String fileTypeArray[] = filePath.split(",");
        String fileType = "";
        if(fileTypeArray != null && fileTypeArray.length > 0) {
          fileType = fileTypeArray[fileTypeArray.length - 1];
        }

對於任意長度的任意拆分字符串c

int i = s.lastIndexOf(c); 
String[] a =  {s.substring(0, i), s.substring(i+c.length())};

您可以使用 apache commons 中的 StringUtils,這是一種提取文件類型的優雅方法。

    String example = "/mnt/sdcard/OG Ron C, Chopstars & Drake - Choppin Ain't The Same-2013-MIXFIEND/02 Drake - Connect (Feat. Fat Pat) (Chopped Not Slopped).mp3";
    String format = StringUtils.substringAfterLast(example, ".");
    System.out.println(format);

程序將在控制台中打印“mp3”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM