我想使用regexp剪切字符串,但不要剪切正则表达式部分......
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"
所以如何添加-Ship01 ??
答案 0 :(得分:3)
尝试使用positive lookbehind:String[] substract2=path.split("(?<=-Ship..)")
。这与模式匹配,但不消耗字符。
答案 1 :(得分:0)
我现在想不出更好的方法。但你可以这样做:
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);
}
}
享受,博罗。