Regex for Extracting Numbers with Optional Commas in C# - Need guide with Large Numbers
I'm confused about I'm working on a project and hit a roadblock. Hey everyone, I'm running into an issue that's driving me crazy. I tried several approaches but none seem to work... I'm trying to use regex in C# to extract numbers from a string, but I need to account for optional commas in large numbers. For example, I want to extract `1,234`, `56,789.99`, and `1000` as valid numbers. However, my current regex is causing issues with numbers formatted with commas, and I'm also working with unexpected behavior when numbers are followed or preceded by other non-numeric characters. Here's the regex I've been using: ```csharp Regex regex = new Regex(@"\b\d{1,3}(,\d{3})*(\.\d+)?\b"); ``` This works for some cases, but it fails when I have numbers like `1,234 apples` or `There are 1000 oranges.`. Instead, I want to match just the numbers without any surrounding text. Additionally, I'm running this on .NET 6.0, and I keep getting unexpected results where it sometimes captures parts of the text instead of just the numbers. I've tried tweaking the regex to account for word boundaries, but I still see issues, especially with the commas. My latest attempt was: ```csharp Regex regex = new Regex(@"(?<=\s|^)(\d{1,3}(,\d{3})*(\.\d+)?)(?=\s|$)"); ``` However, this still doesn't behave as expected. Any suggestions on how I can improve this regex to handle both cases correctly and ensure that it only extracts the numbers, ignoring any surrounding text? Thanks! My development environment is Linux. Am I missing something obvious? For context: I'm using C# on macOS. Any ideas what could be causing this? Am I approaching this the right way? This is for a mobile app running on Ubuntu 22.04. Am I approaching this the right way? What are your experiences with this?