Regex for line splitting does not work properly

I want to split a string into 2 characters without a separator, but Regex split does not work properly

here is my code: -

  String str="splitstring";
    System.out.println("Split.."+str.trim().split("(?<=\\G.{2})").length);
    System.out.println("Split.."+str.trim().split("(?<=\\G.{2})")[0]);
    System.out.println("Split.."+str.trim().split("(?<=\\G.{2})")[1]);

Exit: -

 Split..2

 Split..sp

 Split..litstring
+2
source share
3 answers

It looks like this is a bug with a result threshold limit in your Java environment. Try to get around it by specifying the restriction explicitly:

    String str="splitstring";
    int partsCount = (str.length() + 1) / 2;
    System.out.println("Split.."+str.trim().split("(?<=\\G.{2})", partsCount).length);
    System.out.println("Split.."+str.trim().split("(?<=\\G.{2})", partsCount)[0]);
    System.out.println("Split.."+str.trim().split("(?<=\\G.{2})", partsCount)[1]);
+1
source

I suppose you want to split a string into two equal halves, substrings .. Then this can help !!

System.out.println("Split.."+str.trim().split("(?=\\D)")[0]);
0
source

?

- :

String str = "splitstring";
System.out.println("String-length: " + str.length());
for (int i = 0; i < str.length(); i += 2) { // Increments of 2
  System.out.print("Split.." + str.charAt(i));
  if (i != str.length() - 1) {
    System.out.print(str.charAt(i + 1));
  }
  System.out.println();
}

:

String-length: 11
Split..sp
Split..li
Split..ts
Split..tr
Split..in
Split..g

EDIT: , :

final String str = "splitstring";
System.out.println(Arrays.toString(
    str.split("(?<=\\G.{2})")
));

, . , - , , . , , .


EDIT 2: Jon Skeet , , :

, :

public static List<String> splitEqually(String text, int size) {
    // Give the list the right capacity to start with. You could use an array
    // instead if you wanted.
    List<String> ret = new ArrayList<String>((text.length() + size - 1) / size);

    for (int start = 0; start < text.length(); start += size) {
        ret.add(text.substring(start, Math.min(text.length(), start + size)));
    }
    return ret;
}

, .

EDIT: , :

  • . .
  • , , .
  • , , - ick.
  • The regular expression provided in another answer did not compile at first (invalid escaping) and then did not work. My code worked for the first time. This is more evidence of the convenience of regular expressions against simple code, IMO.
0
source

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


All Articles