var cats = "$22.50 + taxes";
var dogs = "4 Premium Plan Gifts for $150.00 + taxes";
var chat = "3 Forfait supérieur cadea... de 150,00 $ taxes en sus"
最初我以为我正在处理与var cat一致的一致模式。所以我使用这个正则表达式返回美元:cats.match(/^\$.*(?= \+)/);
但事实证明,该字符串将需要几个排列,唯一的确定我知道我想要的数字将以$
开头或以空格' $'
结尾
我可以使用魔法正则表达式返回美元数字吗?
答案 0 :(得分:2)
这将搜索以美元符号开头的数字或小数点分隔符,或后跟空格和美元符号:
cats.match(/(\$[\d.,]+|[\d.,]+ \$)/);
答案 1 :(得分:1)
以下内容将为您提供前导/尾随$:
的所有数字var data = '$22.50 + taxes ' +
'4 Premium Plan Gifts for $150.00 + taxes ' +
'3 Forfait supérieur cadea... de 150,00 $ taxes en sus';
console.log(data.match(/(\$[0-9,.]+|[0-9,.]+\s*\$)/g)); // ["$22.50", "$150.00", "150,00 $"]
故障:
/ # regex start
( # capturing group start
\$ # literal $
[0-9,.]+ # 1 or more of the following characters "0", "1", .., "9", ",", "."
| # or operator (meaning ether left hand side or right hand side needs to be true
[0-9,.]+ # 1 or more of the following characters "0", "1", .., "9", ",", "."
\s* # 0 or more spaces
\$ # literal $
) # capturing group end
/ # regex end
g
如果你想从文本中删除$,你可以使用它:
console.log(data.replace(/(?:\$([0-9,.]+)|([0-9,.])+\s*\$)/g, "$1$2")); // 22.50 + taxes 4 Premium Plan Gifts for 150.00 + taxes 3 Forfait supérieur cadea... de 0 taxes en sus
注意事项:
(?:) # non capturing group (will not produce $1, $2, ...)
答案 2 :(得分:0)
你可以用这个:
var cats = "$22.50 + taxes";
var dogs = "4 Premium Plan Gifts for $150.00 + taxes";
var chat = "3 Forfait supérieur cadea... de 150,00 $ taxes en sus";
console.log( cats.replace(/\$\s*(\d+)/, "$1").replace(/(\d+)\s*\$/, "$1") );
// out: 22.50 + taxes
console.log( dogs.replace(/\$\s*(\d+)/, "$1").replace(/(\d+)\s*\$/, "$1") );
// out: 4 Premium Plan Gifts for 150.00 + taxes
console.log( chat.replace(/\$\s*(\d+)/, "$1").replace(/(\d+)\s*\$/, "$1") );
// out: 3 Forfait supérieur cadea... de 150,00 taxes en sus
或仅使用一次替换:
console.log( chat.replace(/\$\s*(\d+)|(\d+)\s*\$/, "$1$2") )
// out: 3 Forfait supérieur cadea... de 150,00 taxes en sus
如果要替换所有匹配项,请使用'g'(上面的代码只替换第一个代码):
console.log( (cats+" and "+dogs).replace(/\$\s*(\d+)|(\d+)\s*\$/g, "$1$2") );
// out: 22.50 + taxes and 4 Premium Plan Gifts for 150.00 + taxes