Extract digits from a string in Java
Java's String
method replaceAll()
serves you the digi-delight. Using the regex \\D+
, wave adieu to the non-digits:
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:
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:
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:
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.
Was this article helpful?