Java 什么是正确的正则表达式?

Java 什么是正确的正则表达式?,java,regex,Java,Regex,我试图找到一个正则表达式来提取文件名。我的字符串是path/String.mystring 例如 totot/tototo/tatata.tititi/./com.myString 我尝试获取myString 我尝试了String[]test=foo.split([*./././.]])类似的问题也得到了回答。我想说,使用正则表达式获取文件名是错误的做法(例如,如果您的代码试图在Windows文件路径上运行,正则表达式中的斜杠将是错误的做法)-为什么不直接使用: new File(fil

我试图找到一个正则表达式来提取文件名。我的字符串是
path/String.mystring

例如

totot/tototo/tatata.tititi/./com.myString   
我尝试获取
myString


我尝试了
String[]test=foo.split([*./././.]])

类似的问题也得到了回答。我想说,使用正则表达式获取文件名是错误的做法(例如,如果您的代码试图在Windows文件路径上运行,正则表达式中的斜杠将是错误的做法)-为什么不直接使用:

new File(fileName).getName();
要获取文件名,然后使用更简单的拆分提取文件名中需要的部分,请执行以下操作:

String[] fileNameParts = foo.split("\\.");
String partThatYouWant = fileNameParts [fileNameParts.length - 1];

如果要按句点或斜杠拆分,则正则表达式应为

foo.split("[/\\.]")
或者,您可以这样做:

String name = foo.substring(foo.lastIndexOf('.') + 1);

您可以通过以下命令获得最后一个单词:
\w+$

我的字符串是path/String.mystring

如果您的字符串模式是按照上述规则固定的,那么:

string.replaceAll(".*\\.","")

使用
String#subString
String#lastIndexOf
非正则表达式解决方案将是

String path="totot/tototo/tatata.tititi/./com.myString";
String name = path.substring(path.lastIndexOf(".")+1);

也许你应该使用字符串API。大概是这样的:

public static void main(String[] args){
    String path = "totot/tototo/tatata.tititi/./com.myString";
    System.out.println(path.substring(path.lastIndexOf(".") + 1));
}
它适合你的情况吗?使用索引时存在许多问题。但是,如果您始终确信会有一个
,则可以毫无问题地使用此代码。

尝试以下代码:

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class Regexp
{
    public static void main(String args[]) 
    {
    String x = "totot/tototo/tatata.tititi/./com.myString";
    Pattern pattern = Pattern.compile( "[a-z0-9A-Z]+$");
    Matcher matcher = pattern.matcher(x);

    while (matcher.find()) 
        {
        System.out.format("Text found in x: => \"%s\"\n",
                  matcher.group(0));
        }
    }
}

这将使您获得
com.myString
,而不是
myString
。这里的答案是OP实际上并不想要文件名,只是文件的一部分