Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a string at every n-th character

In JavaScript this is how we can split a string at every 3-rd character

"foobarspam".match(/.{1,3}/g) 

I am trying to figure out how to do this in Java. Any pointers?

like image 945
Vijay Dev Avatar asked Feb 19 '10 15:02

Vijay Dev


People also ask

How can I split a string into segments of N characters in Java?

Using the String#split Method As the name implies, it splits a string into multiple parts based on a given delimiter or regular expression. As we can see, we used the regex (? <=\\G. {” + n + “}) where n is the number of characters.

How do I split a string into multiple parts?

Answer: You just have to pass (“”) in the regEx section of the Java Split() method. This will split the entire String into individual characters.

How do you split a string into an N in Python?

You can use the Python string split() function to split a string (by a delimiter) into a list of strings. To split a string by newline character in Python, pass the newline character "\n" as a delimiter to the split() function.


1 Answers

You could do it like this:

String s = "1234567890"; System.out.println(java.util.Arrays.toString(s.split("(?<=\\G...)"))); 

which produces:

[123, 456, 789, 0] 

The regex (?<=\G...) matches an empty string that has the last match (\G) followed by three characters (...) before it ((?<= ))

like image 166
Bart Kiers Avatar answered Sep 20 '22 17:09

Bart Kiers