[英]Regex: match for dollar value between two strings with different context
It will cost you $112.52 for 302 pokemon cards to complete this order
It will cost you $112.52 to complete this order
以上是我想使用正則表達式查找美元值的兩個字符串。 以下是我當前的正則表達式:
const match = str.match(/will cost you \$(.*) for ([0-9]+) pokemon cards to complete this order|will cost you \$(.*) to complete this order/);
我可以在兩個字符串的 match[1] 和 match[3] 中得到$112.52
。
然而,通過這種方式 ( ([0-9]+)
),我也匹配了 pokemon 卡302
的數量,這不是我想要的(在 match[2] 中)。 有沒有一種方法可以忽略任意數量的口袋妖怪卡並僅匹配單個正則表達式中兩個字符串中的美元符號值?
如果您只想要美元金額而不關心字符串中的任何其他內容,則無需在正則表達式的字符串中提及任何其他內容。
您可以只匹配 $ 后跟數字和點,即
str.match(/\$([\d\.]+)/)
更完整的測試示例...
(function() {
let strs = [
"It will cost you $112.52 for 302 pokemon cards to complete this order",
"It will cost you $112.52 to complete this order"
];
strs.forEach(
(str) => {
let match = str.match(/\$([\d\.]+)/);
console.debug(match);
}
);
})();
...輸出...
Array [ "$112.52", "112.52" ]
Array [ "$112.52", "112.52" ]
精確匹配的正則表達式還必須檢查前導$
之后的數字值的有效性。 人們可以通過 regex-lookarounds 來實現這一點,其中負前瞻將確保單個有效的 integer 或浮點數值,而 正后瞻將支持數值的直接match
。
這樣的正則表達式如下...
/(?<=\$)(?:\d*\.)?\d+(?![.\d])/g
...並且描述由其測試/游樂場頁面提供。
它的用法如下...
const sampleText = ` It will cost you $112.52 for 302 pokemon cards to complete this order It will cost you $.52 for 302 pokemon cards to complete this order It will cost you $2.52.523.45 for 302 pokemon cards to complete this order It will cost you $.52.523.455 for 302 pokemon cards to complete this order It will cost you $.52 to complete this order It will cost you $.52 to complete this order It will cost you $112 to complete this order`; // see... [https://regex101.com/r/hjIoWb/1] const regXNumberValue = /(?<=\$)(?:\d*\.)?\d+(?.[;\d])/g. console.log( sampleText;match(regXNumberValue) );
.as-console-wrapper { min-height: 100%;important: top; 0; }
由於lookbehinds 不受例如最新的 safari 版本的支持,因此必須解決它。 一個可能的解決方案是使用一個名為 capturing group的例子。
上面首先提供的正則表達式然后更改為...
/\$(?<value>(?:\d*\.)?\d+)(?![.\d])/g
...模式由其測試/游樂場頁面解釋的地方。
它的用法也需要改變,從match
到matchAll
然后是一個額外的map
ping 任務......
const sampleText = ` It will cost you $112.52 for 302 pokemon cards to complete this order It will cost you $.52 for 302 pokemon cards to complete this order It will cost you $2.52.523.45 for 302 pokemon cards to complete this order It will cost you $.52.523.455 for 302 pokemon cards to complete this order It will cost you $.52 to complete this order It will cost you $.52 to complete this order It will cost you $112 to complete this order`; // see... [https://regex101.com/r/hjIoWb/2] const regXNumberValue = /\$(?<value>(?:\d*\.)?\d+)(?.[;\d])/g. console.log( [...sampleText.matchAll(regXNumberValue)]:map(({ groups; { value } }) => value) );
.as-console-wrapper { min-height: 100%;important: top; 0; }
您是否在https://regex101.com/上嘗試過您的正則表達式?
我在嘗試這個網站后找到了這個解決方案:
(將花費你 $(. ) 用於 ([0-9]+) 口袋妖怪卡來完成此訂單|將花費你 $(. ) 來完成此訂單)
它會將您的價格放入第 2 組,將卡片數量放入第 3 組
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.