2014-09-19 18 views
1

我在嘗試創建工作正則表達式模式來識別文件名字符串時遇到了一些困難。在Java中設置正則表達式模式

Pattern pattern = Pattern.compile("(\\w+)(\\.)(t)(x)(t)(\\s$|\\,)"); 

當使用.find()從我的樣本輸入匹配類,說

"file1.txt,file2.txt " 

,我現在回到真實的,這是很好的,但是其他錯誤輸入也返回true。

這種錯誤輸入的字符串包括諸如:

"file1.txt,,file2.txt " 

"file%.text " 

,因爲我一直在試圖建立他們,我一直在諮詢這個網站,我敢肯定,我失去了一些東西相當明顯不過。 Link

+0

請發佈您的示例輸入和預期輸出。 – xtreak 2014-09-19 13:12:38

+0

*「我沒有完全得到我想要的結果。」*哪些是......? – user1803551 2014-09-19 13:16:13

+0

@ user1803551,我應該爲自己列出的第一個輸入說明一點,我希望它返回true,對於這兩個輔助示例,這些應該返回false。 – JSA 2014-09-19 13:17:31

回答

3

願這可以幫助您:

Pattern pattern = Pattern.compile("(.*?\\.\\w+)(?:,|$)"); 
String files = "file1.txt,file2.txt"; 
Matcher mFile = pattern.matcher(files); 
while (mFile.find()) { 
    System.out.println("file: " + mFile.group(1)); 
} 

輸出:

file: file1.txt 
file: file2.txt 

由於只有.txt文件:(.*?\\.txt)(?:,|$)

+1

這個表達給了我想要的結果,非常感謝你@Nicolas。 – JSA 2014-09-19 13:53:58

2

要驗證文件名列表,您可以採用如下方案:

//         | preceded by start of input, or 
//         | | comma, preceded itself by either word or space 
//         | |    | file name 
//         | |    |  | dot 
//         | |    |  | | extension 
//         | |    |  | | | optional 1 space 
//         | |    |  | | | | followed by end of input 
//         | |    |  | | | |  | or comma, 
//         | |    |  | | | |  | followed itself by word character 
Pattern pattern = Pattern.compile("(?<=^|(?<=[\\w\\s]),)(\\w+)(\\.)txt\\s?(?=$|,(?=\\w))"); 
String input = "file1.txt,file2.txt"; 
String badInput = "file3.txt,,file4.txt"; 
String otherBadInput = "file%.txt, file!.txt"; 
Matcher m = pattern.matcher(input); 
while (m.find()) { 
    // printing group 1: file name 
    System.out.println(m.group(1)); 
} 
m = pattern.matcher(badInput); 
// won't find anything 
while (m.find()) { 
    // printing group 1: file name 
    System.out.println(m.group(1)); 
} 
m = pattern.matcher(otherBadInput); 
// won't find anything 
while (m.find()) { 
    // printing group 1: file name 
    System.out.println(m.group(1)); 
} 

輸出

file1 
file2 
+0

謝謝你對錶達的徹底解釋。 – JSA 2014-09-19 13:57:04

+0

@JoseSalazar不用客氣。 – Mena 2014-09-19 14:07:35

1

簡單的方式:

public boolean validateFileName(String string){ 
     String[] fileNames= string.split(","); 
     Pattern pattern = Pattern.compile("\b[\w]*[.](txt)\b"); /*match complete name, not just pattern*/ 
     for(int i=0;i<fileNames.length;i++){ 
      Matcher m = p.matcher(fileNames[i]); 
      if (!m.matches()) 
       return false; 
     } 
     return true; 
    } 
1
Pattern p = Pattern.compile("((\\w+\\.txt)(,??|$))+"); 

上面的圖案讓 「FILE1.TXT ,, FILE2.TXT」 通過,但沒有得到一個空文件兩個逗號。 正確處理其他字符串「file1.txt,file2.txt」和「文件%txt」。