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?
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With