我真的需要4行代码才能从字符串中间获取值吗?

AAa*_*Aaa 2 java regex string

我需要从文件路径中获取值.假设我的路径看起来像任何其他路径:

c:\SomeFolder\SomeOtherfolder\A_Specific_Folder\what_i_want\another_folder\bla.txt
Run Code Online (Sandbox Code Playgroud)

我可以在运行时推断'A_Specific_Folder'的名称,我需要得到'what_i_want'.我知道'what_i_want'是一个数字

我当前使用这样的正则表达式:

public String getValueThatIneed(String path) {
    String regex = String.format("%s\\\\([0-9]+)\\\\", varContainingNameOfSpecificFolder); 
    Pattern p = Pattern.compile(regex);
    Matcher matcher = compile.matcher(path);
    matcher.find(); \\because otherwise i can't use matcher.start()
    String myValue = path.substring(matcher.start(1), matcher.end(1));
    return myValue;
}
Run Code Online (Sandbox Code Playgroud)

所有这一切只是为了从一个字符串中获取这个tinyValue.现在假设我必须在一个方法中使用它,因为我在10个地方使用它.但是在其中一个地方,我突然需要在stirng上做一些其他操作,这将再次要求我做所有的模式,匹配器的东西,使用相同的正则表达式,只是为了得到matcher.end(1),因为也许这就是全部我需要那边.

有更短的方法吗?

谢谢.

Tho*_*ung 5

我将使用File API并检查父名称:

public String find(File file, String folder) {
    while (file.getParentFile() != null) {
        if(file.getParentFile().getName().equals(folder)) return file.getName();
        file = file.getParentFile();
    }
    return null;
}
Run Code Online (Sandbox Code Playgroud)

或递归等价物:

public static String find(File file, String folder) {
    if(file.getParentFile() == null) return null;
    if(file.getParentFile().getName().equals(folder)) return file.getName();
    return find(file.getParentFile(), folder);
}
Run Code Online (Sandbox Code Playgroud)