我有一个包含文件URL的字符串。从那个字符串我喜欢只获得没有扩展名的文件名。
例如:
http://path/Lists/Test/Attachments/1/Document Test.docx
从那个例子中我想回来:Document Test
我已经有以下模式:
(?<=\/)(\w+)(?=\.\w+(\?.*)*$)
但如果文件名包含空格则无效...如何更改此模式以使其更灵活?
答案 0 :(得分:5)
要仅捕获扩展名前的字符(不限制文件名可能包含的字符),请使用以下命令:
/[^/]*(?=\.[^.]+($|\?))/
答案 1 :(得分:4)
不必使用正则表达式。在这种情况下,lastIndexOF
/
和.
之间的子字符串会为您提供所需的内容。
String data = "Document Testdocx";
int start = data.lastIndexOf('/')+1;
int end = data.lastIndexOf('.');
if (end == -1) end = data.length();
System.out.println(data.substring(start , end));
但如果你真的必须使用正则表达式,你可以尝试这种模式:(?<=/|^)[^./]+(?=\\.\\w+$|$)
答案 2 :(得分:2)
试
String s = "http://path/Lists/Test/Attachments/1/Document Test.docx";
s = s.replaceAll(".+/(.+)\\..+", "$1");
System.out.println(s);
输出
Document Test
答案 3 :(得分:2)
([^?]+)\/([^/?]+)(\.[^.\?]+)(\?.*|)$
即使URL看起来像
http://example.com/foo/bar/baz blah.html?params=true
这可以找到文件名(没有目录)和扩展名。
可能更好的方法是使用java.net.URL解析网址,并使用URL.getPath()。
答案 4 :(得分:1)
而不是(?<=/)(\w+)(?=.\w+(\?.)$)
,请尝试(.+?)(\.[^.]*$|$)