Home > Java > javaTutorial > body text

How to Split a String Between Letters and Digits in Java Using Regular Expressions?

Susan Sarandon
Release: 2024-11-03 11:42:02
Original
161 people have browsed it

How to Split a String Between Letters and Digits in Java Using Regular Expressions?

Splitting Strings Between Letters and Digits in Java

A common task in programming is to split a string that alternates between letters and numbers. For example, given a string like "123abc345def," one might want to separate it into ["123", "abc", "345", "def"].

To achieve this, one can employ regular expressions to capture the pattern. In Java, the following regular expression can be used:

(?<=\D)(?=\d)|(?<=\d)(?=\D)
Copy after login

Explanation:

  • (?<=D): Checks if the current position is preceded by a non-digit.
  • (?=d): Checks if the current position is followed by a digit.
  • |: Logical OR, to handle the reverse pattern (digit followed by non-digit).
  • \d: Matches any digit.
  • \D: Matches any non-digit.

Example usage:

String str = "123abc345def";
String[] splitted = str.split("(?&lt;=\D)(?=\d)|(?&lt;=\d)(?=\D)");

for (String part : splitted) {
    System.out.println(part);
}
Copy after login

This code will print:

123
abc
345
def
Copy after login

Note that the number of letters and numbers in the string can vary. The regular expression will correctly split the string based on the pattern.

The above is the detailed content of How to Split a String Between Letters and Digits in Java Using Regular Expressions?. 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