Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex to extract filename

Tags:

java

regex

I've got a plain text web response and need to extract the filename. Any suggestions for a good 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"
like image 323
ben_muc Avatar asked Dec 04 '22 19:12

ben_muc


1 Answers

You can use this regex to get the filename

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

Code will look like this

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

Explanation of regex

(?<=             # 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
)
like image 171
Narendra Yadala Avatar answered Dec 21 '22 23:12

Narendra Yadala