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

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

Susan Sarandon
Susan SarandonOriginal
2024-11-03 11:42:02166browse

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)

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);
}

This code will print:

123
abc
345
def

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!

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