I am interested to extract the first 10 digits if exists from a long string while disregarding the leading zeros. Additionally if there are only zeroes, return only 1 zero, if there no numbers, return empty string. I wish to match it in a single find
.
For example:
"abcd00111.g2012asd"
should match to"1112012"
"aktr0011122222222222ddd"
should match to"1112222222"
"asdas000000asdasds0000"
should match to"0"
"adsads.cxzv.;asdasd"
should match to""
Here is what I have tried so far: Ideone Demo - code
Pattern p = Pattern.compile("[1-9]{1}+[0-9]{9}");
Matcher m = p.matcher(str);
if (m.find()) {
String match = m.group();
System.out.println(match);
}
The problem is that this regex require 9 sequential digits after the first non zero, and I need any 9 digits (possible non digit chars in between).
Notice that in the code I have if (m.find())
instead of while (m.find())
because I wish to find the match in single run.
UPDATE
base on the comments i understood that it is not possible with regex to do it in single run.
I would like an answer not have to be regex based but most efficient since i will execute this method many times.