java 如何使用正则表达式获取文件扩展名?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29436088/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use regex to get file extension?
提问by user3657834
I'm trying extract a substring from a string that contains a filename or directory. The substring being extracted should be the file extension. I've done some searching online and discovered I can use regular expressions to accomplish this. I've found that ^\.[\w]+$
is a pattern that will work to find file extensions. The problem is that I'm not fully familiar with regular expressions and its functions.
我正在尝试从包含文件名或目录的字符串中提取子字符串。被提取的子字符串应该是文件扩展名。我在网上做了一些搜索,发现我可以使用正则表达式来完成这个。我发现这^\.[\w]+$
是一种可用于查找文件扩展名的模式。问题是我不完全熟悉正则表达式及其功能。
Basically If i have a string like C:\Desktop\myFile.txt
I want the regular expression to then find and create a new string containing only .txt
基本上,如果我有一个像C:\Desktop\myFile.txt
我希望正则表达式那样的字符串,然后查找并创建一个仅包含的新字符串.txt
回答by anubhava
Regex to capture file extension is:
捕获文件扩展名的正则表达式是:
(\.[^.]+)$
Note that dot needs to be escaped to match a literal dot. However [^.]
is a character class with negation that doesn't require any escaping since dot
is treated literally inside [
and ]
.
请注意,点需要转义以匹配文字点。然而,[^.]
是一个带有否定的字符类,不需要任何转义,因为dot
在[
和内部按字面处理]
。
\. # match a literal dot
[^.]+ # match 1 or more of any character but dot
(\.[^.]+) # capture above test in group #1
$ # anchor to match end of input
回答by Touchstone
You could use String class split() function. Here you could pass a regular expression. In this case, it would be "\.". This will split the string in two parts the second part will give you the file extension.
您可以使用 String 类 split() 函数。在这里你可以传递一个正则表达式。在这种情况下,它将是“\.”。这会将字符串分成两部分,第二部分将为您提供文件扩展名。
public class Sample{
public static void main(String arg[]){
String filename= "c:\abc.txt";
String fileArray[]=filename.split("\.");
System.out.println(fileArray[fileArray.length-1]); //Will print the file extension
}
}
回答by Frank Andres
If you don't want to use RegEx you can go with something like this:
如果您不想使用 RegEx,您可以使用以下方法:
String fileString = "..." //this is your String representing the File
int lastDot = fileString.lastIndexOf('.');
String extension = fileString.subString(lastDot+1);