基于Java中第n个字符串的出现拆分字符串

时间:2017-07-19 13:54:42

标签: java regex string

如何根据除第n次出现以外的分隔符的第n(例如:秒)出现来分割字符串,应保留所有其他分隔符

I / P:

 String name="This is my First Line";
 int delimiter=" ";
 int count=3;//This is a dynamic value

O / P:

String firstpart=This is my
String Secondpart=First Line

5 个答案:

答案 0 :(得分:4)

由于正则表达式的限制,您无法将其拆分为1行代码,但您可以分为2行:

String firstPart = name.replaceAll("^((.*?" + delimiter + "){" + count + "}).*", "$1");
String secondPart = name.replaceAll("^(.*?" + delimiter + "){" + count + "}(.*)", "$2");

答案 1 :(得分:1)

我得到了这样的

String name="This is my First Line";

 int count=3;

 String s1,s2;

 String arr[]=name.split();//default will be space

 for(i=0;i<arr.length;i++)

   if(i<count)

    s1=s1+arr[i]+" "

   else 

    s2=s2+arr[i]+" "

答案 2 :(得分:1)

只需使用indexOf搜索分隔符并重复此操作,直到找到 count -times。这是一个片段:

String name = "This is my First Line";
String delimiter = " ";
int count = 3;

// Repeativly search for the delimiter
int lastIndex = -1;
for (int i = 0; i < count; i++) {
    // Begin to search from the position after the last matching index
    lastIndex = name.indexOf(delimiter, lastIndex + 1);

    // Could not be found
    if (lastIndex == -1) {
        break;
    }
}

// Get the result
if (lastIndex == -1) {
    System.out.println("Not found!");
} else {
    // Use the index to split
    String before = name.substring(0, lastIndex);
    String after = name.substring(lastIndex);

    // Print the results
    System.out.println(before);
    System.out.println(after);
}

现在输出

This is my
 First Line

注意最后一行开头的空格(分隔符),如果你想在最后使用下面的代码,你可以省略它

// Remove the delimiter from the beginning of 'after'
String after = ...
after = after.subString(delimiter.length());

答案 3 :(得分:0)

static class FindNthOccurrence
{
    String delimiter;

    public FindNthOccurrence(String del)
    {
        this.delimiter = del;
    }

    public int findAfter(String findIn, int findOccurence)
    {
        int findIndex = 0;
        for (int i = 0; i < findOccurence; i++)
        {
            findIndex = findIn.indexOf(delimiter, findIndex);
            if (findIndex == -1)
            {
                return -1;
            }
        }
        return findIndex;
    }
}

FindNthOccurrence nth = new FindNthOccurrence(" ");
String string = "This is my First Line";
int index = nth.nthOccurrence(string, 2);
String firstPart = string.substring(0, index);
String secondPart = string.substring(index+1);

答案 4 :(得分:-1)

就这样, 在 Java 8 中测试并完美运行

public String[] split(String input,int at){
    String[] out = new String[2];
    String p = String.format("((?:[^/]*/){%s}[^/]*)/(.*)",at);
    Pattern pat = Pattern.compile(p);
    Matcher matcher = pat.matcher(input);
       if (matcher.matches()) {
          out[0] = matcher.group(1);// left
          out[1] = matcher.group(2);// right
       }
    return out;
} 

//Ex: D:/folder1/folder2/folder3/file1.txt
//if at = 2, group(1) = D:/folder1/folder2  and group(2) = folder3/file1.txt