Home >Java >javaTutorial >How to Split Strings at Regular Intervals in Java?

How to Split Strings at Regular Intervals in Java?

Linda Hamilton
Linda HamiltonOriginal
2024-11-20 00:12:02196browse

How to Split Strings at Regular Intervals in Java?

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...)
  • (?<=\G) ensures that the match begins at the start of the string or any subsequent match.
  • ... matches any three characters.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn