Javascript 使用javascript中的正则表达式从文本中过滤掉数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3097048/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:15:43  来源:igfitidea点击:

Filter out numbers out of a text using regular expressions in javascript

javascriptregexstring

提问by zoom_pat277

What will be the best way using javascript regular expression to get numbers out of text.. e.g.... I have "$4,320 text/followme" and I want to get 4320 out of this. However I want to avoid numbers after first occourance of an alphabet or any non alphabet other than a comma ','

使用 javascript 正则表达式从文本中获取数字的最佳方法是什么……例如……我有“$4,320 text/followme”,我想从中得到 4320。但是,我想避免在首次出现字母表或除逗号 ',' 以外的任何非字母表后使用数字

so that if i have $4,320 t234ext/followme it will still return me 4320. The input will always have $ sign at the beginning

所以如果我有 $4,320 t234ext/followme 它仍然会返回给我 4320。输入的开头总是有 $ 符号

so the regular expression should return

所以正则表达式应该返回

 ,320 text/followme          returns  4320
 ,320 t3444ext/followme      return   4320
 ,320 /followme              return   4320
 20 text/followme           return   4320
 20 t3444ext/followme       return   4320
 20 /follow4me              return   4320

回答by SilentGhost

string.split(/ /)[0].replace(/[^\d]/g, '')

回答by Weston C

The simplest regular expression you're possiblylooking for is \D(any character that's not a numeral. There's a few of these "negated" expressions -- \dmatches a numeral, \Dmatches non-numerals. \wmatches "word" characters (alphanumeric plus the underscore), \Wmatches non-numeric. \smatches whitespace, \Smatches non-whitespace characters).

可能正在寻找的最简单的正则表达式是\D(任何不是数字的字符。有一些“否定”表达式 -\d匹配数字,\D匹配非数字。\w匹配“单词”字符(字母数字加下划线) ,\W匹配非数字。\s匹配空格,\S匹配非空格字符)。

So:

所以:

str = ',320 text/folowme';
number = str.replace(/\D/g,'');

should yield '4320' inside of number. The 'g' is important. It says do a globalsearch/replace for all instances of that regex. Without it, you'll just lose the dollar sign. :)

应该在数字内部产生“4320”。“g”很重要。它说对该正则表达式的所有实例进行全局搜索/替换。没有它,你只会失去美元符号。:)

Note that if you've got negative numbers or rationals (which can have two non-numeric characters in their representation, '-' and '.'), your problem gets a little bit harder. You could do something like:

请注意,如果您有负数或有理数(它们的表示形式中可以有两个非数字字符,“-”和“.”),您的问题会变得更难一些。你可以这样做:

number = str.replace(/[^-.0-9]/g,'');

Which will work as long your numbers are well formed -- as nobody does anything crazy like '4-5.0-9aaaa4z.2'.

只要您的数字格式正确,这将起作用——因为没有人会做任何像“4-5.0-9aaaa4z.2”这样的疯狂事情。

To be safe, you could run that list bit through parseIntor parseFloat:

为了安全起见,您可以通过parseInt或运行该列表parseFloat

number = parseFloat(str.replace(/[^-.0-9]/g,''));

UPDATE

更新

I spaced the requirement to avoid including subsequent numbers. If whitespace reliably delimits the end of the number you want, as it does in the examples, you could add a space or \s to the negated character class on that last example I gave, so it'd be something like this:

我将要求隔开以避免包含后续数字。如果空格可靠地分隔了您想要的数字的结尾,就像在示例中那样,您可以在我给出的最后一个示例的否定字符类中添加一个空格或 \s,所以它会是这样的:

number = parseFloat(str.replace(/[^-.0-9\s]/g,''));

and it'll strip out the extra numbers just fine.

它会很好地去除多余的数字。

UPDATE 2

更新 2

After thinking about this for a bit, using parseFloatmeans that you don't have to strip out everything -- just all the non-numeric characters beforethe number you want, and commas. So we can break this into two simpler regexes (and probably faster, especially since one of them is non-global). And then parseFloatwill discard trailing non-numeric input for you.

考虑了一下之后,使用parseFloat意味着您不必删除所有内容——只需删除您想要的数字之前的所有非数字字符和逗号。因此,我们可以将其分解为两个更简单的正则表达式(并且可能更快,特别是因为其中一个是非全局的)。然后parseFloat将为您丢弃尾随的非数字输入。

number = parseFloat(str.replace(/,/g,'').replace(/^[^-0-9]*/,''));

回答by Robert Hui

Here's a slightly more complicated regex.

这是一个稍微复杂的正则表达式。

2nd line: It checks for the initial '$', and allows any combination of digits (0-9) and commas thereafter.

第 2 行:它检查初始的 '$',并允许其后的数字 (0-9) 和逗号的任意组合。

3rd line: Removes the leading $ and any commas in the numeric value.

第 3 行:删除数值中的前导 $ 和任何逗号。

I don't know off-hand, but I want to say that JavaScript supports grouping, and it may be possible to nab just the numeric value with commas in the match statement, simplifying the replace statement to just remove the commas.

我不知道,但我想说 JavaScript 支持分组,并且可以在 match 语句中只使用逗号来获取数值,简化替换语句以仅删除逗号。

var str=",320 t3444ext/followme";
var regex = /^$([0-9,])*/g;
var matchedNum = str.match(regex)[0].replace(/[$,]/g, '');

回答by ChaosPandion

function parseNumber(input) {
    var r = "", i = 0, c = "", s = input + " ";
    if (s.charAt(0) === "$") {
        i++;
    } 
    while (i < s.length) {        
        c = s.charAt(i++);
        if (c < "0" || c > "9") {
            if (c === ",") {
                continue;
            }
            break;
        }
        r += c;
    }
    return r;
}