QaMantra: How to get Numeric Value from AlphaNumeric String in Java

How to get Numeric Value from AlphaNumeric String in Java

Program with using Regex :

package com.abof.scripts;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class JavaProgram {
 /**
  * 
  * @author   QaMantra
  */
 //Java Program to get Numeric Value from AlphaNumeric Without  //Regex
 public static void main(String[] args) {
  
  String str=" abc d 1234567890pqr 54897";

  Pattern p = Pattern.compile("(\\d+)");
  Matcher m = p.matcher(str);
  while(m.find())
  {
      System.out.println("Numeric Value : "+m.group(1));
  }
}}
output :                                                        Numeric Value : 1234567890
Numeric Value : 54897

Program without using Regex :


package com.abof.scripts;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class JavaProgram {
 /**
  * 
  * @author   QaMantra
  */
 
 //Java Program to get Numeric Value from AlphaNumeric Without Regex
 public static void main(String[] args) {
  String str = "abc d 1234567890pqr 54897";
     StringBuilder myNumbers = new StringBuilder();
     for (int i = 0; i < str.length(); i++) {
         if (Character.isDigit(str.charAt(i))) {
             myNumbers.append(str.charAt(i));
             System.out.println(str.charAt(i) + " is a digit.");
         } else {
             System.out.println(str.charAt(i) + " not a digit.");
         }
     }                                                   System.out.println("Numeric Value : " + myNumbers.toString());
 }}
output :                                                        a not a digit.
b not a digit.
c not a digit.
  not a digit.
d not a digit.
  not a digit.
1 is a digit.
2 is a digit.
3 is a digit.
4 is a digit.
5 is a digit.
6 is a digit.
7 is a digit.
8 is a digit.
9 is a digit.
0 is a digit.
p not a digit.
q not a digit.
r not a digit.
  not a digit.
5 is a digit.
4 is a digit.
8 is a digit.
9 is a digit.
7 is a digit.
Your numbers: 123456789054897

No comments: