user615927
user615927

Reputation: 153

Cutting String by using regexp

I want to cut the string using regexp, but not to cut the regexp part...

String path ="house/room/cabinet/my_books/bought/2011/adventure/Black-Ship01/312 pages/...";
String[] substract=path.split("my_");
path=substract1[1].toString();// books/bought/2011/adventure/Black-Ship01/312 pages/...
String[] substract2=path.split("-Ship.."); //split using -Ship and two random simbols
path=substract[1].toString();

RESULT:   path= "books/bought/2011/adventure/Black"
Should be path= "books/bought/2011/adventure/Black-Ship01"

so how to add -Ship01 ??

Upvotes: 0

Views: 190

Answers (2)

Boro
Boro

Reputation: 7943

I cannot think of a better way right now. But you could do something like that:

public class NewClass
{
    public static void main(String[] args)
    {
        String finalStr = "";
        String patternStr = "(-Ship..)";
        String path ="house/room/cabinet/my_books/bought/2011/adventure/Black-Ship01/312 pages/...";
        String[] substract2 = path.split(patternStr);       
        System.out.println("substract2="+Arrays.toString(substract2));      
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(path);    
        matcher.find();
        System.out.println("g0="+matcher.group(0));
        finalStr = substract2[0]+matcher.group(0);
        System.out.println("finalStr="+finalStr);
      }     
}

Enjoy, Boro.

Upvotes: 0

NPE
NPE

Reputation: 500367

Try using positive lookbehind: String[] substract2=path.split("(?<=-Ship..)"). This matches the pattern but doesn't consume the characters.

Upvotes: 3

Related Questions