Home > Java > javaTutorial > body text

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

DDD
Release: 2024-10-27 21:26:30
Original
941 people have browsed it

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>
Copy after login

This will produce the following result:

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

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!