数字后跟单词的正则表达式 [英] Regex for a number followed by a word
问题描述
在 JavaScript 中,数字后跟单词的正则表达式是什么?我需要捕捉数字和单词并在计算后替换它们.
In JavaScript, what would be the regular expression for a number followed by a word? I need to catch the number AND the word and replace them both after some calculation.
以下是示例形式的条件:
Here are the conditions in a form of example:
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
- 当然,123.555、0.365、5454.1 也是数字.
为了使事情更简单,这个词是一个特定的词(例如美元|欧元|日元).
- Of course 123.555, 0.365, 5454.1 are numbers too.
For making things simpler the word is a specific one (e.g dollar|euro|yen).
好的..谢谢大家...这是我目前所做的基本功能:
OK.. Thank you all... Here is the basic function I made so far:
var text = "foo bar 15 美元.bla bla..";var 货币 = {美元:0.795};
var text = "foo bar 15 dollars. bla bla.."; var currencies = { dollars: 0.795 };
document.write(text.replace(/\b((?:\d+.)?\d+) *([a-zA-Z]+)/, function(a,b,c){返回货币[c] ?b * 货币[c] + '欧元' : a;}));
document.write(text.replace(/\b((?:\d+.)?\d+) *([a-zA-Z]+)/, function(a,b,c){ return currencies[c] ? b * currencies[c] + ' euros' : a; } ));
推荐答案
试试这个:
/\b(\d*\.?\d+) *([a-zA-Z]+)/
这也将匹配
.5 测试
之类的东西.如果你不想这样,使用这个:That will also match stuff like
.5 tests
. If you don't want that, use this:/\b((?:\d+\.)?\d+) *([a-zA-Z]+)/
并避免匹配5.5.5美元":
And to avoid matching "5.5.5 dollars":
/(?:[^\d]\.| |^)((?:\d+\.)?\d+) *([a-zA-Z]+)/
这篇关于数字后跟单词的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!