Search code examples
javascriptregexword-boundary

Word Boundary match float followed by optional space


I am trying to match a float followed by an optional space followed by a list of symbols which can be represented as follows

price of rldtoken
420 rld.token 0.28 btc
42.37 rldtoken to xrp
42.37rldtoken to xmr
cost of rldtoken
10 btc 12.47 rldtoken to xmr
whatisrldtoken
btcc price
btc cost
0.2btc

I am currently using this regex

((?:0|[1-9]\d*)?(?:\.\d+)?)\s*\b(rld[\W_]*token|btcc|btc|ark|xmr|xrp)\b

broken down as

((?:0|[1-9]\d*)?(?:\.\d+)?) Match float
\s* Match 0 or more spaces
\b(rld[\W_]*token|btcc|btc|ark|xmr|xrp)\b Match words

which matches all but 42.37rldtoken to xrp and 0.2btc, I am assuming this has to do something with space and word boundaries

If I remove the word boundary, it matches whatisrldtoken which I dont want to match.

Some directions on how to proceed would be super appreciated

EDIT Everything in action HERE


Solution

  • You may use tis regex:

    (?:(\.\d+|\b\d+(?:\.\d+)?)\s*|\b)(rld[\W_]*token|btcc|btc|ark|xmr|xrp)\b
    

    Updated RegEx Demo

    To match floating point number it is more accurate to match number starting with dot separately in alternation rather than keeping both parts optional which will result in matching an empty string.