JavaScript 正则表达式 - 从单词旁边提取数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4193536/
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 11:18:42  来源:igfitidea点击:

JavaScript Regular Expression - Extract number from next to word

javascriptregexstring

提问by Tom

Been a long time since I have touched regular expressions. It's simple but I am pulling my hair out over it.

很久没有接触正则表达式了。这很简单,但我正在把头发拉出来。

I have a string as follows that I get from the DOM "MIN20, MAX40". I want to be able to use regex in JavaScript to extract the integer next to MINand the integer next to MAXand put into separate variables minand max. I cannot figure a way to do it.

我有一个从 DOM 获取的字符串,如下所示"MIN20, MAX40"。我希望能够在 JavaScript 中使用正则表达式来提取旁边MIN的整数MAX和旁边的整数并将其放入单独的变量minmax. 我想不出办法做到这一点。

Thanks to who ever helps me, you will be a life saver!

感谢曾经帮助过我的人,您将成为救生员!

Cheers

干杯

回答by codaddict

You can use:

您可以使用:

var input   = "MIN20, MAX40";
var matches = input.match(/MIN(\d+),\s*MAX(\d+)/);
var min = matches[1];
var max = matches[2];

JSfiddle link

JSfiddle 链接

回答by Tom

I think this would work:

我认为这会奏效:

var matches = "MIN20, MAX40".match(/MIN(\d+), MAX(\d+)/);
var min = matches[1]; 
var max = matches[2];

回答by Tim Down

The following will extract numbers following "MIN" and "MAX" into arrays of integers called minsand maxes:

下面将把 "MIN" 和 "MAX" 后面的数字提取到名为minsand的整数数组中maxes

var mins = [], maxes = [], result, arr, num;
var str = "MIN20, MAX40, MIN50";

while ( (result = /(MIN|MAX)(\d+)/g.exec(str)) ) {
    arr = (result[1] == "MIN") ? mins : maxes; 
    num = parseInt(result[2]);
    arr.push(num);
}

// mins: [20, 50]
// maxes: [40]

回答by Gabriele Petrioli

This should do the trick.

这应该可以解决问题。

var str='MIN20, MAX40';

min = str.match(/MIN(\d+),/)[1];
max = str.match(/MAX(\d+)$/)[1];

回答by Gabriele Petrioli

var str = "MIN20, MAX40";
value = str.replace(/^MIN(\d+),\sMAX(\d+)$/, function(s, min, max) {
    return [min, max]
});

console.log(value); // array