正则表达式提取文件名

ben*_*muc 4 java regex

我有一个纯文本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"
Run Code Online (Sandbox Code Playgroud)

Nar*_*ala 14

您可以使用此正则表达式来获取文件名

(?<=filename=").*?(?=")
Run Code Online (Sandbox Code Playgroud)

代码将如下所示

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

正则表达式的解释

(?<=             # 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
)
Run Code Online (Sandbox Code Playgroud)