How to get string before .(dot) and after /(last)

2020-02-29 18:36发布

I have a string like this:

"core/pages/viewemployee.jsff"

From this code, I need to get "viewemployee". How do I get this using Java?

标签: java
5条回答
SAY GOODBYE
2楼-- · 2020-02-29 18:43

Suppose that you have that string saved in a variable named myString.

String myString = "core/pages/viewemployee.jsff";
String newString = myString.substring(myString.lastIndexOf("/")+1, myString.indexOf("."));      

But you need to make same control before doing substring in this one because, if there aren't those characters you will get from lastIndexOf(), or indexOf() a "-1" that will break your substring invocation.

I suggest to you to look for the Javadoc documentation.

查看更多
兄弟一词,经得起流年.
3楼-- · 2020-02-29 18:49

These are file paths, right? Consider using File.getName(), especially if you already have the File object:

File file = new File("core/pages/viewemployee.jsff");
String name = file.getName(); // --> "viewemployee.jsff"

And to remove the extension:

String res = name.split("\\.[^\\.]*$")[0]; // --> "viewemployee"

With this we can handle strings like "../viewemployee.2.jsff".

The regex matches the last dot, zero or more non-dots, and the end of the string. Then String.split() treats these as a delimiter, and ignores them. The array will always have one element, unless the original string is ..

查看更多
霸刀☆藐视天下
4楼-- · 2020-02-29 18:51

You can split the string first with "/" so that you can have each folder and the file name got separated. For this example, you will have "core", "pages" and "viewemployee.jsff". I assume you need the file name without the extension, so just apply same split action with "." seperator to the last token. You will have filename without extension.

String myStr = "core/pages/viewemployee.bak.jsff";

String[] tokens = myStr.split("/");
String[] fileNameTokens = tokens[tokens.length - 1].split("\\.");

String fileNameStr = "";

for(int i = 0; i < fileNameTokens.length - 1; i++) {
    fileNameStr += fileNameTokens[i] + ".";
}

fileNameStr = fileNameStr.substring(0, fileNameStr.length() - 1);

System.out.print(fileNameStr) //--> "viewemployee.bak"
查看更多
够拽才男人
5楼-- · 2020-02-29 18:53

Below will get you viewemployee.jsff

int idx = fileName.replaceAll("\\", "/").lastIndexOf("/");
String fileNameWithExtn =  idx >= 0 ? fileName.substring(idx + 1) : fileName;

To remove the file Extension and get only viewemployee, similarly

idx = fileNameWithExtn .lastIndexOf(".");
String filename = idx >= 0 ? fileNameWithExtn.substring(0,idx) : fileNameWithExtn ;
查看更多
啃猪蹄的小仙女
6楼-- · 2020-02-29 19:07

You can solve this with regex (given you only need a group of word characters between the last "/" and "."):

    String str="core/pages/viewemployee.jsff";
    str=str.replaceFirst(".*/(\\w+).*","$1");
    System.out.println(str); //prints viewemployee
查看更多
登录 后发表回答