Home > Java > javaTutorial > How to Split a String with Letters and Numbers into Alternating Segments in Java?

How to Split a String with Letters and Numbers into Alternating Segments in Java?

Susan Sarandon
Release: 2024-10-28 11:03:49
Original
859 people have browsed it

How to Split a String with Letters and Numbers into Alternating Segments in Java?

Separating Letters and Numbers in a String

In Java, you can encounter the need to split a string that contains both letters and digits into alternating segments. For instance, given the string "123abc345def," you might aim for the following result:

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

To achieve this precise separation, you can employ the following regular expression:

str.split("(?<=\D)(?=\d)|(?<=\d)(?=\D)");
Copy after login

This pattern splits the string at specific points based on two conditions:

  • (?<=D)(?=\d): Matches positions immediately after a non-digit character (D) and immediately before a digit (d). This condition identifies the start of a numerical segment.
  • (?<=d)(?=\D): Matches positions immediately after a digit and immediately before a non-digit character. This condition identifies the start of a letter segment.

By splitting the string at these positions, you can isolate the alternating segments of letters and numbers.

Explanation of the Regexp:

  • \D: Matches any non-digit character.
  • \d: Matches any digit character.
  • (?<=): Positive lookbehind, matching a pattern immediately before the current position.
  • (?=): Positive lookahead, matching a pattern immediately after the current position.

Example Usage:

String str = "123abc345def";
String[] x = str.split(&quot;(?&lt;=\D)(?=\d)|(?&lt;=\d)(?=\D)&quot;);
Copy after login

After executing the above code, the x array will contain the alternating segments as desired:

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

This technique enables you to efficiently separate letters and digits in a string, allowing you to process them according to their types.

The above is the detailed content of How to Split a String with Letters and Numbers into Alternating Segments 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template