Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most efficient way to extract all the (natural) numbers from a string

Users may want to delimit numbers as they want.

What is the most efficient (or a simple standard function) to extract all the (natural) numbers from a string?

like image 690
Eduardo Avatar asked Jan 30 '10 21:01

Eduardo


People also ask

How do I extract numbers from a string in Python?

To find numbers from a given string in Python we can easily apply the isdigit() method. In Python the isdigit() method returns True if all the digit characters contain in the input string and this function extracts the digits from the string. If no character is a digit in the given string then it will return False.


2 Answers

You could use a regular expression. I modified this example from Sun's regex matcher tutorial:

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

public class Test {

    private static final String REGEX = "\\d+";
    private static final String INPUT = "dog dog 1342 dog doggie 2321 dogg";

    public static void main(String[] args) {
       Pattern p = Pattern.compile(REGEX);
       Matcher m = p.matcher(INPUT); // get a matcher object
       while(m.find()) {
           System.out.println("start(): "+m.start());
           System.out.println("end(): "+m.end());
       }
    }
}

It finds the start and end indexes of each number. Numbers starting with 0 are allowed with the regular expression \d+, but you could easily change that if you want to.

like image 156
Mark Byers Avatar answered Sep 30 '22 03:09

Mark Byers


I'm not sure I understand your question exactly. But if all you want is to pull out all non-negative integers then this should work pretty nicely:

String foo = "12,34,56.0567 junk 6745 some - stuff tab tab 789";
String[] nums = foo.split("\\D+");

// nums = ["12", "34", "56", "0567", "6745", "789"]

and then parse out the strings as ints (if needed).

like image 41
Rob Van Dam Avatar answered Sep 30 '22 02:09

Rob Van Dam