我正在尝试提取字符串中的测量值。
这是我目前的做法:
const string = '10mL 5mL';
const regex = `([0-9]*mL)|([0-9]*g)|([0-9]*gallon)|([0-9]*kg)|([0-9]*L)|([0-9]*mg)|([0-9]*patches)`;
console.log(string.matches(regex));
所以我期望输出为 ['10mL', '5mL']
。当我检查日志时,它只提取第一个 10mL
[ '10mL',
'10mL',
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
index: 0,
input: '10mL 5mL',
groups: undefined ]
关于我在这里缺少什么的任何提示?谢谢!
最佳答案
您要查找的函数是match
而不是matches
。您也可以像这样以紧凑的形式编写正则表达式,
/(\d+\s*(?:mL|g|gallon|kg|L|mg|patches))/g
试试这个 JS 代码,
const string = '10mL 5mL 25 mL';
const regex = /(\d+\s*(?:mL|g|gallon|kg|L|mg|patches))/g;
console.log(string.match(regex));
好的 Timothy Hawkins,您可以在正则表达式中将 \d+
替换为 \d+(\.\d+)?
,它也会捕获十进制数。
演示如下,
const string = '10mL 5mL 25 mL 12.5kg, 5.2mL';
const regex = /(\d+(\.\d+)?\s*(?:mL|g|gallon|kg|L|mg|patches))/g;
console.log(string.match(regex));
很抱歉延迟回复,由于工作量太大,大部分时间都不活跃:(
关于Javascript:如何提取字符串中的测量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54248204/