Blogs

Extract Integer Numbers from String in Java without Regular Expression
Author:Dixanta Bahadur Shrestha

In the digital world, data can be available in various form and sometimes its a hectic job of extracting required information if format is irregular. String is a very powerful data type in Java programming and it can hold any types of data i.e numbers, characters etc.

I have written an algorithm, which can extract number data from text/string using Java Programming Language.  In this program I have not used Regular Expression or any kind of third party libraries hence I believe code can be easy to read.


package com.cibt.code;
/**
 * Author: Dixanta Bahadur Shrestha
 * Creators Institute of Business & Technology
 */
public class App {
    public static void main(String[] args) {
        String text="this string has number 12 and 15 and 67";
        String numValue="";
        int textLength=text.length();
        for(int i=0;i < textLength;i++){
            int ascii=text.charAt(i);
            if(ascii >=48 && ascii <=(48+9)){
                numValue +=(char)ascii;
            }
        }
        int result=Integer.parseInt(numValue);
        System.out.println(result);
    }    
}
Output
121517
Happy Coding !!!

Previous