I have the text like "It's the 145 of 13221 items". I need to fetch all the number("145 and 13221") of text on one time. I want to use regex to do this. What is the regex like? "\d+" is not work fine.
+3
A:
\d+
works fine. Depending on language, you may have to escape the slash to "\\d+"
, e.g. in Java.
String text = "It's the 145 of 13221 items";
Matcher m = Pattern.compile("\\d+").matcher(text);
while (m.find()) {
System.out.println(m.group());
}
// prints "145", "13221"
You need to figure out how to find regex matches in a string in your language, but the pattern \d+
will match a non-zero sequence of consecutive digits.
In Javascript, you can do something like this:
function findDigitSequences(s) {
var re = new RegExp("\\d+", "g");
return s.match(re);
}
polygenelubricants
2010-05-13 17:11:59
I know "\d+". But it cann't fetch number in one time. For example, "It's the 145 of 13221 items" it will give me "145,1,14,45,4,5 and so on".
Gordian Yuan
2010-05-13 17:18:35
@Gord: you mean given a string `"145"`, you want to explode it to all the different substrings `"145", "1", "14", "45", "4", "5"`? That's not regex, that's just listing substrings of a string from all legal indices `i, j`.
polygenelubricants
2010-05-13 17:21:38
No. I just want 145 and 13221.In java, it work fine. But I working with JavaScript.
Gordian Yuan
2010-05-13 17:23:52
Thanks your findDigits function. I work perfect fine!
Gordian Yuan
2010-05-13 17:34:00
A:
^[\D\w]+([\d]+)[\D\w]+([\d]+).+$
Capture Groups:
- 145
- 13221
Sorry my brain was off when I wrote that
Aren
2010-05-13 17:12:35
Thanks. But I try it on http://www.regextester.com/ it doesn't work.
Gordian Yuan
2010-05-13 17:19:21
+1
A:
You need to use something like ^[^\d]*(\d+)[^\d]*(\d+)[^\d]*$
. Depends on what flavor of regex you are using.
This regex matches:
- Zero or more non-numeric characters at the start ("It's the ")
- One or more numeric characters in capture group #1 ("145")
- Zero or more non-numeric characters (" of ")
- One or more numeric characters in capture group #2 ("13221")
- Zero or more non-numeric characters at the end ("items")
Jon
2010-05-13 17:13:04
Yeah! I try it. It's work. Thanks a lot. I will find how it work later.I need to back to work now. Thank you.
Gordian Yuan
2010-05-13 17:27:31