简体   繁体   English

如何获取文本数?

[英]How to fetch number of the text?

I have the text like "It's the 145 of 13221 items". 我的文字是“这是13221个项目中的145个”。 I need to fetch all the number("145 and 13221") of text on one time. 我需要一次提取所有数量的文本(“ 145和13221”)。 I want to use regex to do this. 我想使用正则表达式来做到这一点。 What is the regex like? 正则表达式是什么样的? "\\d+" is not work fine. “ \\ d +”不能正常工作。

\\d+ works fine. \\d+工作正常。 Depending on language, you may have to escape the slash to "\\\\d+" , eg in Java. 根据语言的不同,您可能必须将斜杠转义为"\\\\d+" ,例如在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. 您需要弄清楚如何用您的语言在字符串中查找正则表达式匹配项,但是\\d+模式将匹配非零连续数字序列。


In Javascript, you can do something like this: 在Javascript中,您可以执行以下操作:

function findDigitSequences(s) {
    var re = new RegExp("\\d+", "g");
    return s.match(re);
}

You need to use something like ^[^\\d]*(\\d+)[^\\d]*(\\d+)[^\\d]*$ . 您需要使用类似^[^\\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") 捕获组#1中的一个或多个数字字符(“ 145”)
  3. Zero or more non-numeric characters (" of ") 零个或多个非数字字符(“”的“”)
  4. One or more numeric characters in capture group #2 ("13221") 捕获组#2中的一个或多个数字字符(“ 13221”)
  5. Zero or more non-numeric characters at the end ("items") 结尾处的零个或多个非数字字符(“项目”)
^[\D\w]+([\d]+)[\D\w]+([\d]+).+$

Capture Groups: 捕获组:

  1. 145 145
  2. 13221 13221

Sorry my brain was off when I wrote that 对不起,当我写那封信时

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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