2011-11-11 196 views
4

我有一個純文本的Web響應,並需要提取文件名。 對於良好RegEx的任何建議?正則表達式提取文件名

Total parts : 1 
Name : file 
Content Type : text/plain 
Size : 1167 
content-type : text/plain 
content-disposition : form-data; name="file"; filename="test_example.txt" 
+0

的說明請參見各行,如果它包含()''文件名'然後只是'分割()'它與文件名=' –

回答

14

您可以使用此正則表達式來獲取文件名

(?<=filename=").*?(?=") 

代碼看起來像這樣

String fileName = null; 
Pattern regex = Pattern.compile("(?<=filename=\").*?(?=\")"); 
Matcher regexMatcher = regex.matcher(requestHeaderString); 
if (regexMatcher.find()) { 
    fileName = regexMatcher.group(); 
} 

正則表達式

(?<=    # Assert that the regex below can be matched, with the match ending at this position (positive lookbehind) 
    filename="  # Match the characters 「filename="」 literally 
) 
.    # Match any single character that is not a line break character 
    *?    # Between zero and unlimited times, as few times as possible, expanding as needed (lazy) 
(?=    # Assert that the regex below can be matched, starting at this position (positive lookahead) 
    "    # Match the character 「"」 literally 
) 
+0

什麼將是正則表達式 內容處置:form-data; NAME = 「文件」; filename = test_example.txt 即不帶引號 – mohitum