2015-11-19 58 views
1
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 cats一致的模式。所以我用這個正則表達式返回美元:cats.match(/^\$.*(?= \+)/);從字符串中拉出美元

但事實證明,該字符串將需要數排列的唯一婷肯定的,我知道的是,我想要麼開始$或空間美元' $'到底有多少

是否有一個神奇的正則表達式,我可以用它來返回美元數?

+1

[像這樣的東西(http://jsfiddle.net/hpykuy59/1/)? –

回答

2

這將搜索數字或小數點分隔符或者由前面是美元符號,或者一個空格和一個美元符號後面:

cats.match(/(\$[\d.,]+|[\d.,]+ \$)/); 

https://regex101.com/r/lI1fB3/2

+0

這太好了。謝謝 –

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 
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, ...)