Igor
Igor

Reputation: 1331

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

Upvotes: 1

Views: 3668

Answers (3)

callumacrae
callumacrae

Reputation: 8433

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

Upvotes: 4

Ricardo Lohmann
Ricardo Lohmann

Reputation: 26320

string.replace(/\d+(?=\s*(\w+))/, function(match) {
    return 'your replace';
});

Upvotes: 0

Austin Greco
Austin Greco

Reputation: 33544

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?)/ );

Upvotes: 1

Related Questions