How to Extract Digits from a String in Java
Table of Contents
When you're working with strings that you don't control, they can come with both numbers and alphabetical characters.
If you only want the digits, you will have to extract it out of the string.
In this post, we'll learn how to extract digits from a string in Java.
How to Extract Digits from a String
To start, let's define a string that includes numbers:
JAVAString string = "Hello World 123";
The easiest way to extract the numbers is to remove all the non-numeric characters with the replaceAll
method.
We can pass in a regex expression that will match all non-numeric characters, and replace it with a blank string.
JAVAString string = "Hello World 123";
String digits = string.replaceAll("[^0-9]", "");
System.out.println(digits);
BASH123
The magic is in the regular expression that we pass in as the first parameter of the replaceAll
method.
Because it will only match non-numeric characters, the only thing left are numerical ones.
Another way to accomplish the same task is to first compile the expression and then reuse it to replace the string.
JAVAimport java.util.regex.Matcher;
import java.util.regex.Pattern;
class HelloWorld {
public static void main(String[] args) {
String string = "Hello World 123";
Pattern pattern = Pattern.compile("[^0-9]");
Matcher matcher = pattern.matcher(string);
String digits = matcher.replaceAll("");
System.out.println(digits);
}
}
BASH123
Conclusion
In this post, we learned how to extract digits from a string in Java.
Simply use the replaceAll
method to remove all non-numeric characters and replace them with a blank string.
Thanks for reading and happy coding!
- Getting Started with TypeScript
- Managing PHP Dependencies with Composer
- Create an RSS Reader in Node
- How to build a Discord bot using TypeScript
- Learn how to use v-model with a custom Vue component
- Using Puppeteer and Jest for End-to-End Testing
- Getting Started with Handlebars.js
- Getting User Location using JavaScript's Geolocation API
- Learn how to build a Slack Bot using Node.js
- Using Push.js to Display Web Browser Notifications
- Building a Real-Time Note-Taking App with Vue and Firebase
- Setting Up Stylus CSS Preprocessor