我有以下字串,我試圖與 RegEx 匹配:
286,879 in Home & Kitchen (See Top 100 in Home & Kitchen)
339 in Cardboard Cutouts
2,945 in Jigsaws (Toys & Games)
這是我的代碼/正則運算式:
const matches = text.matchAll(/(?<!Top )([\d,|] ) in[\s\n ]([\w&'\s] )/g);
for(const match of matches){
const rank = parseInt(match[1].replace(/[^\d]/g, ''));
const category = match[2].trim()
console.log(`${category} = ${rank}`)
}
但是,它應該匹配的唯一部分是:286,879 in Home & Kitchen, 339 in Cardboard Cutouts,2,945 in Jigsaws (Toys & Games)
預期的輸出應該是:
Home & Kitchen = 286879
Cardboard Cutouts = 339
Jigsaws = 2945
如何調整正則運算式以忽略100 in Home & Kitchen字串
謝謝
uj5u.com熱心網友回復:
正則運算式組:
result- 來自輸入(行)的一條記錄data- 數字(包括,)cat- 分類名稱extra- 被忽略
JS
- 替換
result為重新排序的cat($3)=和data($2) - 替換
,為empty
const regex = /(?<result>(?<data>^[\d|,] )(?: in )(?<cat>. ?)(?<extra>\s (?:\(. ?\)?)?))$/gm;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('(?<result>(?<data>^[\\d|,] )(?: in )(?<cat>. ?)(?<extra>\\s (?:\\(. ?\\)?)?))$', 'gm')
const str = `286,879 in Home & Kitchen (See Top 100 in Home & Kitchen)
339 in Cardboard Cutouts
2,945 in Jigsaws (Toys & Games)`;
const subst = `$3 = $2`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst).replace(',', '');
console.log('Substitution result: ', result);
uj5u.com熱心網友回復:
如果你只想排除括號中的東西,你可以嘗試這樣的事情:
/^([\d,|] ) in[\s\n ]([\w&'\s] )(\s*\(.*\)\s*)?$/gm
并忽略第三個捕獲組
uj5u.com熱心網友回復:
您可能會使用 2 個捕獲組:
(?<!Top\s )\b(\d (?:,\d )?)\s in\s ([^()\n]*[^\s()])
解釋
(?<!Top\s )負向后看,斷言Top后面沒有 1 個空格字符直接位于當前位置的左側。\b防止部分單詞匹配的單詞邊界(\d (?:,\d )?)捕獲組 1,將 1 個數字與可選,和 1 個數字匹配\s in\sin1 空格字符之間的匹配(捕獲組 2[^()\n]*[^\s()]匹配換行符以外的可選字符和()
)關閉組 2
正則運算式演示
const regex = /(?<!Top\s )\b(\d (?:,\d )?)\s in\s ([^()\n]*[^\s()])/;
[
"const str = `286,879 in Home & Kitchen (See Top 100 in Home & Kitchen)",
"339 in Cardboard Cutouts",
"2,945 in Jigsaws (Toys & Games)`;"
].forEach(s => {
const m = s.match(regex);
if (m) {
console.log(`${m[2]} = ${m[1].replace(",", "")}`)
}
})
請注意, using\s也可以匹配換行符。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/469172.html
