Explain Codes LogoExplain Codes Logo

Extract digits from a string in Java

java
string-manipulation
java-8
performance
Nikita BarsukovbyNikita Barsukov·Dec 15, 2024
TLDR

Java's String method replaceAll() serves you the digi-delight. Using the regex \\D+, wave adieu to the non-digits:

String digits = "a1b2c3".replaceAll("\\D+", ""); System.out.println(digits); // 123 - No more secret codes!

This high-speed digit extraction leaves behind a clean string of digits.

If your performance-o-meter rankings of code matters, then precompiled patterns are your calling. For repeated tasks, they are faster than a kid spotting ice cream:

Pattern digitPattern = Pattern.compile("\\D+"); String digits = digitPattern.matcher("a1b2c3").replaceAll(""); System.out.println(digits); // 123 - You rang '123'?

Easy steps without regex

When regex sounds like rocket science, go for the good old iteration. Do some legwork with a StringBuilder and pocket the digits:

public String extractDigits(String input) { StringBuilder sb = new StringBuilder(); for (char c : input.toCharArray()) { if (c >= '0' && c <= '9') { sb.append(c); // "Lead with your digits!" - Every Number Ever } } return sb.toString(); }

This code is as stubborn as a mule, only acknowledging ASCII digits and bypassing tricky unicode digits.

Library-enhanced solutions

Some of us like having fancy tools. If you don't mind some extra library love, Guava's CharMatcher is here to do the heavy lifting:

String digits = CharMatcher.inRange('0', '9').retainFrom("a1b2c3"); System.out.println(digits); // 123 - Roll the magic number!

However, do check your 'extra load allowance'. You don't want your project to carry unnecessary luggage just for trivial tasks.

Winning favours with the community

If earning brownie points matter, then a vote for regex is a vote for popularity. An upvote-flush answer attests to the charm of regex. They're loved for their brevity, and liked for their problem-solving prowess.

Dodge the landmines

While extracting digits, keep an eyepatch for locales and formats. They can turn a harmless '1,234.5' into a digit-extracting monster. Be a smart Samaritan with input validation and avoid overflowing your integer basket.

Performance playoff

Performance-enthusiasts should set the stage for a showdown between CharSequence or a Java 8+ Stream with filter. Run benchmarks and determine the fastest digit-pulling gun in your code town.

The future-proofing guide

Stay atop the Java evolution wave with pattern matching improvements in Java 17 and String API upgrades. Building clean and maintainable code ensures your string-digit extraction routine avoids the dinosaur's fate.