views:

60

answers:

3

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
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
@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
No. I just want 145 and 13221.In java, it work fine. But I working with JavaScript.
Gordian Yuan
Thanks your findDigits function. I work perfect fine!
Gordian Yuan
A: 
^[\D\w]+([\d]+)[\D\w]+([\d]+).+$

Capture Groups:

  1. 145
  2. 13221

Sorry my brain was off when I wrote that

Aren
Thanks. But I try it on http://www.regextester.com/ it doesn't work.
Gordian Yuan
+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:

  1. Zero or more non-numeric characters at the start ("It's the ")
  2. One or more numeric characters in capture group #1 ("145")
  3. Zero or more non-numeric characters (" of ")
  4. One or more numeric characters in capture group #2 ("13221")
  5. Zero or more non-numeric characters at the end ("items")
Jon
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