Regex Not Matching Multiple Currency Formats in JavaScript - implementing Optional Decimal Places
I'm trying to match various currency formats in a string using JavaScript's regex capabilities, but I keep working with issues when optional decimal places are involved. Specifically, I want to match formats like '$100', '$100.00', '€200', '£150.5', and I also want to ensure it captures the currency symbol correctly. Here’s the regex pattern I’m currently using: ```javascript const regex = /[£$€]\d+(\.\d{1,2})?/g; ``` However, this regex fails to match cases like '£150.50', which is valid because the decimal part should be optional. I also noticed it doesn't account for spaces between the currency symbol and the amount, such as '€ 200'. I've tried modifying the pattern like this: ```javascript const regex = /[£$€]\s?\d+(\.\d{1,2})?/g; ``` This successfully matches '€ 200' but fails to capture amounts like '£150.50'. The following test string illustrates the question: ```javascript const testString = 'I owe you $100 and € 200, but I also have £150.50 and £150.5.'; const matches = testString.match(regex); console.log(matches); ``` The output is `['$100', '€ 200']`, missing the '£150.50' and '£150.5' entries entirely. How can I adjust my regex pattern to capture all variations of these currency formats, including optional decimal places and potential spaces? I’m using Node.js v14.17.0, and I’d appreciate any insights on best practices for crafting this regex too.