Splitting Strings at Intervals in Java
Splitting a string at specific intervals can be a common task in programming. In Java, achieving this using regular expressions offers a versatile and efficient solution.
Problem Statement
Consider the task of splitting a string at every 3rd character. In JavaScript, this can be accomplished using the following expression:
"foobarspam".match(/.{1,3}/g)
This expression successfully splits the string "foobarspam" into ["foo", "bar", "spa", "m"].
Java Implementation
To achieve the same result in Java, we can employ a similar approach using the Pattern and Matcher classes:
String input = "1234567890"; String[] arr = input.split("(?<=\G...)");
Explanation
The regular expression used here is:
(?<=\G...)
The (?<= ) construct essentially asserts that the preceding pattern (in this case, three characters) occurs before the match. By using the split method, we obtain an array of strings where each element represents a 3-character substring.
The above is the detailed content of How to Split Strings at Regular Intervals in Java?. For more information, please follow other related articles on the PHP Chinese website!