Sven
Sven

Reputation: 1133

Parsing a path to get desired name

I'm trying to parse a given path to a project or a package in the project such that I can construct a useful name from it.

I've been toying around with regex but I am having troubles.

Examples of what I want (supplied string => desired one):

"C:/Users/IDPWorkspace/moneyTestProject/bin"  => moneyTestProject
"C:/Users/IDPWorkspace/moneyTestProject/bin/moneyScenario" => moneyTestProject_moneyScenario

So far I've got

path.toString().substring(path.toString().indexOf("bin")+4)
               .replace('/', '.').replace('\\', '.');` 

which does fine in getting everything past bin but not sure how to do the other stuff...

Upvotes: 0

Views: 47

Answers (2)

nolegs
nolegs

Reputation: 608

I don't have a Java compiler available, but you can try this pseudo-ish code:

String[] delimiters = {"/", "\\"};
String[] tokens = path.Split(delimiters);

StringBuilder result = new StringBuilder();

for(int i = 0; i < tokens.Length; i++)
{
    if(tokens[i].toLower().equals("bin") && (i > 0))
    {
        result.append(tokens[i-1]);
        for(int j = i+1; j < tokens.Length; j++)
        {
            result.append("_" + tokens[j]);
        }
        break;
    }
}

String finalPath = result.toString();

Upvotes: 1

brandonscript
brandonscript

Reputation: 73034

Could you use /([^/]*)/bin/?(.*) ? Replace with backreference 1 and 2 like so:

http://regex101.com/r/cZ4lM3

You would then need to strip a trailing _ in the case the 2 doesn't match. (Or test for 2 and join with _)

Upvotes: 0

Related Questions