Java extract number from string using regex , you will get best solution.During working with Java programming,you are facing some situation where you need to print/get numbers from a message or From Database tables or From Excel data etc.In order to work or extract numbers from String we are going to use regular expression and replaceAll method in Java.
ALSO READ - Create a File in Java
Java extract number from string
Let's see the below example to extract number from a string using regular expressions in java
Example:
package com.practice.javs;
public class GetNumbers {
public static void main(String[] args) {
String name= "rajesh123456k";
String numerics = name.replaceAll("[^0-9]", "");
System.out.println(numerics);
}
}
As per above Java program,i have used one String which is having alphabets and numbers.In above example simply i have stored in another String i.e numeric's with replaceAll method for name string and used [^0-9] regular expression means retrieve only numbers between 0 to 9.
Output:
123456
replaceAll
Replaces each sub-string of this string which matches the given regular expressions with the given replacement([^0-9]). An invocation of replaceAll method of the form str.replaceAll(regex, repl) fields exactly the same result as per the expression.Topics you have learned
1.How to get digits from String2.How to use Regular Expression
3.replaceAll method in java
0 Komentar
Penulisan markup di komentar