Regex for a number followed by a word

懵懂的女人 提交于 2021-02-17 02:47:45

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!