Home  >  Article  >  Java  >  How can I split a string into alternating groups of letters and digits in Java?

How can I split a string into alternating groups of letters and digits in Java?

DDD
DDDOriginal
2024-10-27 21:26:30998browse

How can I split a string into alternating groups of letters and digits in Java?

Separating Digits and Letters in a String

Question:

How can we split a string into alternating groups of letters and digits in Java, considering that the length of each group may vary?

Solution:

To achieve this in Java, you can utilize the split() method with a regular expression that defines the separation pattern. The appropriate pattern is (?<=D)(?=d)|(?<=d)(?=D), which operates as follows:

  • (?<=D)(?=d) identifies positions between a non-digit (D) and a digit (d).
  • (?<=d)(?=D) identifies positions between a digit and a non-digit.

By matching these positions, the regular expression effectively splits the string at the designated intervals. Here's an example code:

<code class="java">String a = "123abc345def";
String[] x = a.split("(?<=\D)(?=\d)|(?<=\d)(?=\D)");</code>

This will produce the following result:

x[0] = "123"
x[1] = "abc"
x[2] = "345"
x[3] = "def"

Note that the number of groups (letters and digits) may vary, accommodating inputs like "1234a5bcdef."

The above is the detailed content of How can I split a string into alternating groups of letters and digits 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