在問這個問題之前,我研究了這個,

我不完全確定這是否正確。如果它是正確的,第二個問題是它正在拾取空格。即使我可以稍后替換空格,但我想知道是否有辦法在沒有空格的情況下提取數字
var x = 'The cost of 2 burgers and 3 drinks are $15'
var y = x.match(/((?!([\$]))^)\d |(?:[^\$])\b\d /gm);
var z = y.toString().replace(/ /gm,'');
先感謝您。
uj5u.com熱心網友回復:
您可以使用一些標準的 js 陣列/字串操作來獲得所需的輸出:
const strings = [
'2 burgers and 3 drinks would be $15',
'The cost of 2 burgers and 3 drinks are $15',
'The foo did bar to baz'
];
const results = strings.map(str =>
(str.match(/.?\d /g) || []) // Match all numbers with their preceding character
.filter(s => s[0] !== '$') // Filter out matches that start with '$'
.map(s => s.trim())); // Trim the results.
console.log(results);
這里的一大優勢是可讀性。如果一年后你回到這段代碼,弄清楚它的作用是非常微不足道的。
uj5u.com熱心網友回復:
您可以通過匹配價格和匹配和捕獲其他數字來提取數字,同時只收集后者:
var x = 'The cost of 2 burgers and 3 drinks are $15'
var re = /\$\d (?:\.\d )?|(\d (?:\.\d )?)/g
var output=[], m;
while (m =re.exec(x)) {
if (m[1]) {
output.push(m[1])
}
}
console.log(output); // => [ "2", "3" ]
請參閱正則運算式演示。這里,
\$\d (?:\.\d )?- 匹配$,一位或多位數字,然后可選出現.和 一位或多位數字|- 或者(\d (?:\.\d )?)- 捕獲組 1:一位或多位數字,然后可選出現.和 一位或多位數字。
uj5u.com熱心網友回復:
如果數字前面應該有空格,則可以匹配空格或使用斷言字串的開頭(?:\s|^)并使用捕獲組 1 中的數字(\d )。
然后您可以使用組 1 提取數字,m[1]在示例代碼中用 表示。
(?:\s|^)(\d )
正則運算式演示
const regex = /(?:\s|^)(\d )/g;
[
'2 burgers and 3 drinks would be $15',
'The cost of 2 burgers and 3 drinks are $15'
].forEach(s => console.log(Array.from(s.matchAll(regex), m => m[1])))
如果在它之前可以有一個不是美元符號或數字的其他字符,以防止部分匹配。
(?:[^\d$]|^)(\d )
正則運算式演示
const regex = /(?:[^\d$]|^)(\d )/g;
[
'2 burgers and 3 drinks would be $15',
'The cost of 2 burgers and 3 drinks are $15 A12'
].forEach(s => console.log(Array.from(s.matchAll(regex), m => m[1])))
uj5u.com熱心網友回復:
我傾向于支持最簡單的方法。
如果您在 IE11 中使用 JavaScript,那么您的 RegEx 選項非常有限。最簡單的選擇是使用包含 的正則運算式$,然后$在匹配后過濾掉數字:
const inputString = "5 hotdogs are $3, 7 eggs are $1 and 3 cheese blocks are $10";
const regexp = /(\$?\d )/g
console.log(
inputString.match(regexp).filter( v => v[0] !== "$" )
);
可以修改正則運算式以包含可選的空格等,但原則成立。有時,RegEx 最簡單的方法是將其視為起點,而不是試圖讓它給出最終答案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/316109.html
標籤:javascript 正则表达式
