
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to extract numbers from a string using regular expressions?
You can match numbers in the given string using either of the following regular expressions −
“\\d+” Or, "([0-9]+)"
Example 1
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ExtractingDigits { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter sample text: "); String data = sc.nextLine(); //Regular expression to match digits in a string String regex = "\\d+"; //Creating a pattern object Pattern pattern = Pattern.compile(regex); //Creating a Matcher object Matcher matcher = pattern.matcher(data); System.out.println("Digits in the given string are: "); while(matcher.find()) { System.out.print(matcher.group()+" "); } } }
Output
Enter sample text: this is a sample 23 text 46 with 11223 numbers in it Digits in the given string are: 23 46 11223
Example 2
import java.util.regex.Matcher; import java.util.regex.Pattern; public class Just { public static void main(String[] args) { String data = "abc12def334hjdsk7438dbds3y388"; //Regular expression to digits String regex = "([0-9]+)"; //Creating a pattern object Pattern pattern = Pattern.compile(regex); //Creating a Matcher object Matcher matcher = pattern.matcher(data); System.out.println("Digits in the given string are: "); while(matcher.find()) { System.out.print(matcher.group()+" "); } } }
Output
Digits in the given string are: 12 334 7438 3 388
- Related Questions & Answers
- How to extract data from a string with Python Regular Expressions?
- How to extract numbers from a string using Python?
- How to extract numbers from text using Python regular expression?
- How to remove consonants from a string using regular expressions in Java?
- How to remove vowels from a string using regular expressions in Java?
- How to split a string using regular expressions in C#?
- Remove Leading Zeroes from a String in Java using regular expressions
- How to extract numbers from a string in Python?
- Return a specific MySQL string using regular expressions
- How to extract each (English) word from a string using regular expression in Java?
- Extract decimal numbers from a string in Python
- How to extract date from text using Python regular expression?
- How to write unicode regular expressions to find a substring in a string using Python?
- How to extract certain substring from a string using Java?
- How to extract floating number from text using Python regular expression?
Advertisements