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?
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.
Answer: You just have to pass (“”) in the regEx section of the Java Split() method. This will split the entire String into individual characters.
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.
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 ((?<= )
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With