How to split a string into any other delimiter

There is a line

String str = "ggg;ggg;nnn;nnn;aaa;aaa;xxx;xxx;";

How to break it down into lines like this "Yyyy, yyyy;" "NNN, NNN;" "Ahh, ahh;" "Xxx, xxx;" ???????

+4
source share
5 answers

Using Regex

    String input = "ggg;ggg;nnn;nnn;aaa;aaa;xxx;xxx;";
    Pattern p = Pattern.compile("([a-z]{3});\\1;");
    Matcher m = p.matcher(input);
    while (m.find())
        // m.group(0) is the result
        System.out.println(m.group(0));

Will output

GGG; GGG;

NNN; NNN;

aaa, aaa;

xxx xxx;

+1
source

Separate and connect them.

 public static void main(String[] args) throws Exception {
        String data = "ggg;ggg;nnn;nnn;aaa;aaa;xxx;xxx;";
        String del = ";";
        int splitSize = 2;

        StringBuilder sb  = new StringBuilder();
        for (Iterable<String> iterable : Iterables.partition(Splitter.on(del).split(data), splitSize)) {
            sb.append("\"").append(Joiner.on(del).join(iterable)).append(";\"");
        }
        sb.delete(sb.length()-3, sb.length());
        System.out.println(sb.toString());

    }

Link: Split a line at every third comma in Java

+1
source

, , , .

, , , ArrayList Stack.

, /([a-z])\1\1/.

, if:

(stack.peek().substring(0,index).equals(temp))

public static Stack<String> splitString(String text, char split) {
    Stack<String> stack = new Stack<String>();
    int index = text.indexOf(split);
    while (index != -1) {
        String temp = text.substring(0, index);
        if (!stack.isEmpty()) {
            if (stack.peek().charAt(0) == temp.charAt(0)) {
                temp = stack.pop() + split + temp;
            }
        }
        stack.push(temp);
        text = text.substring(index + 1);
        index = text.indexOf(split);
    }
    return stack;
}
+1

split :

String data="ggg;ggg;nnn;nnn;aaa;aaa;xxx;xxx;";
String [] array=data.split("(?<=\\G\\S\\S\\S;\\S\\S\\S);");
  • S:
  • G: / , , , .
  • ? < =: , .
+1

, .

, :

  • .

: , - , .

Of course, following other answers to "real" splitting, more flexible; but (theoretically), you can just go ahead and make a bunch of tweaks to access all the elements.

0
source

Source: https://habr.com/ru/post/1657153/


All Articles