简体   繁体   中英

Regex for a number followed by a word

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 (eg 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; } ));

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]+)/

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?)/ );
string.replace(/\d+(?=\s*(\w+))/, function(match) {
    return 'your replace';
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM