CodexBloom - Programming Q&A Platform

Regex optimization guide for Matching Floating Point Numbers in Python 3.9 with Commas

👀 Views: 68 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-13
regex python-3.x string-manipulation Python

Quick question that's been bugging me - I've been struggling with this for a few days now and could really use some help... I'm trying to use regex to match floating point numbers in a string that can use commas as decimal separators, such as '3,14' or '2,5'. My intention is to extract these numbers from a larger string, but I'm working with issues with the regex not capturing them correctly. Here's the regex pattern I tried: ```python import re pattern = r'\b\d+[,]\d+\b' ``` I used this pattern expecting it to match any sequence of digits followed by a comma and more digits. However, when I run the following code: ```python text = 'The measurements are 3,14 and 2,5. Also, consider 4.0 and 5 for completeness.' matches = re.findall(pattern, text) print(matches) ``` I only get an empty list as output. I've confirmed that the string contains the numbers in the specified format, but the regex fails to capture them. Additionally, I noticed that my pattern does not consider cases where the floating point number could be part of a larger word, such as 'value3,14more'. Could someone suggest an improvement or a completely different approach? I'm using Python 3.9.0, and I want to ensure this works efficiently across various inputs. Thanks in advance for your help! How would you solve this? What am I doing wrong?