javascript - how to reduce complexity in regex? -


i have a regex finds kind of money denoted in dollars,like $290,usd240,$234.45,234.5$,234.6usd

(\$)[0-9]+\.?([0-9]*)|usd+[0-9]+\.?([0-9]*)|[0-9]+\.?[0-9]*usd|[0-9]+\.?[0-9]*(\$) 

this seems works, how can avoid complexity in regex?

it possible make regex bit shorter collapsing currency indicators:
can usd or $ amount instead of usd amount or $ amount. results in following regex:

((\$|usd)[0-9]+\.?([0-9]*))|([0-9]+\.?[0-9]*(\$|usd)) 

im not sure if you'll find less complex, @ least it's easier read because it's shorter

the character set [0-9] can replaced \d -- character class matches digit -- making regex shorter.
doing this, regex follows:

((\$|usd)\d+\.?\d*)|(\d+\.?\d*(\$|usd)) 

update:

  • according @toto regex more performant using non-capturing groups (also removed not-necessary capture group pointed out @simon má¶œkenzie):

    (?:\$|usd)\d+\.?\d*|\d+\.?\d*(?:\$|usd) 
  • $.0 amounts not matched regex @gangnus pointed out. updated regex fix this:

    ((\$|usd)((\d+\.?\d*)|(\.\d+)))|(((\d+\.?\d*)|(\.\d+))(\$|usd)) 

    note changed \d+\.?\d* ((\d+\.?\d*)|(\.\d+)): either matches 1 or more digits, optionally followed dot, followed 0 or more digits; or dot followed 1 or more digits.

    without unnecessary capturing groups , using non-capturing groups:

    (?:\$|usd)(?:\d+\.?\d*|\.\d+)|(?:\d+\.?\d*|\.\d+)(?:\$|usd) 

Comments

Popular posts from this blog

python - Selenium remoteWebDriver (& SauceLabs) Firefox moseMoveTo action exception -

html - How to custom Bootstrap grid height? -

transpose - Maple isnt executing function but prints function term -