简体   繁体   中英

Extracting specific parts of a String

I am trying to get the "work" part of this string:

 String test = "\prod\mp\incoming\users\work\test.java";

I have been trying to do it this way:

  String result = test.substring(test.lastIndexOf("\\")+1 , test.length());

But this is returning "test.java"

try:

String test = "\\prod\\mp\\incoming\\users\\work\\test.java";
String[] s = test.split("\\");
result = s[s.length-2];

Here is the split method signature:

public String[] split(String regex);

It splits this string around matches of the given regular expression and returns an array of String containing the matches. In your case you need to get the second to last match which is the the match with index s.length-2 since the last element in the array s has the index s.length-1

Break your one-liners down into sensible parts. Instead of this...

String result = test.substring(test.lastIndexOf("\\") + 1 , test.length());

... try this...

int lastSlashIndex = test.lastIndexOf("\\");
int endIndex = test.length();
String result = test.substring(lastSlashIndex + 1, endIndex);

It then becomes painfully obvious that your substring goes from the last slash to the end of the string. So how do you fix it? First, you need to describe the problem properly. There are two possible things you are trying to do, and I have no idea which is correct:

  • You want to find the fifth item in the path.
  • You want to find the second to last item in the path.

I'll tackle the first, and if it turns out to be the second, you should be able to follow what I've done and do it yourself.

// Get the fifth item in the path
String[] items = test.split("\\");
String result = items[4];

Add some error checking to prevent an array index out of bounds exception.

String[] items = test.split("\\");
String result = "";
if (items.length > 4)
    result = items[4];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM