使用正则表达式从字符串中提取权重和价格值



>我有以下字符串。我想要三个正则表达式,为每个字符串提取权重、度量单位和第一个价格。它们需要可推广到相同形式的其他字符串。
'250g - £3.55£12.3 per kg'提取物"250"、"g"和"3.55"'500g - £7.15£14.8 per kg'提取"500"、"g"和"7.15"'2kg - £14.85£20.98 per kg'提取"2"、"kg"和"14.85">

此正则表达式应提取所需的三个值:

/(d+)(k?g) - £([^£]+)/

请参阅 https://regex101.com/r/A7npHN/1/

const regex = /(d+)(g|kg)s*-s*£(d+.d+)/gm;
const str = `250g - £3.55£12.3 per kg
500g - £7.15£14.8 per kg
2kg - £14.85£20.98 per kg`;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}

您可以使用以下正则表达式。

^(?<wt>d+)(?<wt_unit>S+)s+-D+(?<price>d+.d+)

演示

Javascript的正则表达式引擎执行以下操作。

^                  match beginning of line
(?<wt>d+)         match 1+ digits in cap grp 'wt'
(?<wt_unit>S+)    match 1+ chars other than w'space in cap grp 'wt_unit'
s+-D+            match 1+ w'space chars, '-', 1+ chars other than digits
(?<price>d+.d+) match 1+ digits, '.', 1+ digits in cap grp 'price'

最新更新