[英]Regex for a number followed by a word
在JavaScript中,一个单词后跟一个单词的正则表达式是什么? 我需要记住数字和单词并在计算后将它们替换掉。
以下是一个示例形式的条件:
123 dollars => Catch the '123' and the 'dollars'.
foo bar 0.2 dollars => 0.2 and dollars
foo bar.5 dollar => 5 and dollar (notice the dot before 5)
foo bar.5.6 dollar => 5.6 and dollar
foo bar.5.6.7 dollar => skip (could be only 0 or 1 dot)
foo bar5 dollar => skip
foo bar 5dollar => 5 and dollar
5dollar => 5 and dollar
foo bar5dollar => skip
为了使事情更简单,这个词是特定的(例如,美元|欧元|日元)。
好的..谢谢大家...这是我到目前为止所做的基本功能:
var text =“foo bar 15美元.bla bla ..”; var currency = {dollar:0.795};
document.write(text.replace(/?b((?:\\ d +。)?\\ d +)*([a-zA-Z] +)/,函数(a,b,c){return currency [E] ?b * currency [c] +'euros':a;}));
尝试这个:
/\b(\d*\.?\d+) *([a-zA-Z]+)/
这也将匹配.5 tests
类的东西。 如果您不想这样,请使用:
/\b((?:\d+\.)?\d+) *([a-zA-Z]+)/
并避免匹配“5.5.5美元”:
/(?:[^\d]\.| |^)((?:\d+\.)?\d+) *([a-zA-Z]+)/
快速尝试:
text.match( /\b(\d+\.?\d*)\s*(dollars?)/ );
如果你想做美元/美元和欧元/欧元那么:
text.match( /\b(\d+\.?\d*)\s*(dollars?|euros?)/ );
还\\s
将匹配所有空白,包括标签..如果你只想要空格,则只是把一个空间,而不是(像其他答案):
text.match( /\b(\d+\.?\d*) *(dollars?|euros?)/ );
string.replace(/\d+(?=\s*(\w+))/, function(match) {
return 'your replace';
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.