Home >Java >javaTutorial >How to Split a String at Regular Intervals in Java?
Splitting Strings at Regular Intervals in Java
Splitting a string at every n-th character is a common operation in programming. In Java, there exist multiple ways to achieve this. However, one effective approach is to utilize the split() method, which allows for fine-tuning the splitting behavior.
Similar to the example provided in JavaScript, where a string is split into groups of three characters, we can replicate this functionality in Java using the following snippet:
String s = "1234567890"; System.out.println(java.util.Arrays.toString(s.split("(?<=\G...)")));
This code achieves the desired result by splitting the string s at every third character. The split() method takes a regular expression as its parameter, and the expression provided in this case is:
(?<=\G...)
Understanding the Regular Expression
Breaking down the regular expression part by part:
Explanation
The split() method utilizes the pattern provided in the regular expression to identify the split points within the string. The lookbehind assertion ensures that the split occurs at positions that have three consecutive characters preceding them. The G anchor helps maintain the correct split points as the method progresses through the string.
As a result, the output of the code is:
[123, 456, 789, 0]
This demonstrates how to effectively split a string at every n-th character in Java using the split() method and a custom regular expression.
The above is the detailed content of How to Split a String at Regular Intervals in Java?. For more information, please follow other related articles on the PHP Chinese website!