问题
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
- 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 dollars. bla bla.."; var currencies = { dollars: 0.795 };
document.write(text.replace(/\b((?:\d+.)?\d+) *([a-zA-Z]+)/, function(a,b,c){ return currencies[c] ? b * currencies[c] + ' euros' : a; } ));
回答1:
Try this:
/\b(\d*\.?\d+) *([a-zA-Z]+)/
That will also match stuff like .5 tests
. If you don't want that, use this:
/\b((?:\d+\.)?\d+) *([a-zA-Z]+)/
And to avoid matching "5.5.5 dollars":
/(?:[^\d]\.| |^)((?:\d+\.)?\d+) *([a-zA-Z]+)/
回答2:
quick try:
text.match( /\b(\d+\.?\d*)\s*(dollars?)/ );
if you want to do dollar/dollars and euro/euros then:
text.match( /\b(\d+\.?\d*)\s*(dollars?|euros?)/ );
also \s
would match all whitespace including tabs.. if you just want spaces then just put a space instead (like the other answer):
text.match( /\b(\d+\.?\d*) *(dollars?|euros?)/ );
回答3:
string.replace(/\d+(?=\s*(\w+))/, function(match) {
return 'your replace';
});
来源:https://stackoverflow.com/questions/12221637/regex-for-a-number-followed-by-a-word