简体   繁体   中英

How to fetch number of the text?

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.

\\d+ works fine. Depending on language, you may have to escape the slash to "\\\\d+" , eg 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);
}

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")
^[\D\w]+([\d]+)[\D\w]+([\d]+).+$

Capture Groups:

  1. 145
  2. 13221

Sorry my brain was off when I wrote that

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM