Skip to content

Instantly share code, notes, and snippets.

@karenpayneoregon
Created May 14, 2024 13:49
Show Gist options
  • Save karenpayneoregon/4c6beda00f31104c591d643808dfe656 to your computer and use it in GitHub Desktop.
Save karenpayneoregon/4c6beda00f31104c591d643808dfe656 to your computer and use it in GitHub Desktop.
Get numbers values from string
using System.Globalization;
using System.Text.RegularExpressions;
namespace ConsoleApp1;
internal partial class Program
{
static void Main(string[] args)
{
var input = "Enter anything 12 and I will try 44 to detect any number (leave empty 1 to exit):";
var foundNumbers = TryFindTheNumbers(input);
if (foundNumbers.Count <= 0) return;
Console.WriteLine(string.Join(",", foundNumbers));
Console.ReadLine();
}
private static List<string> TryFindTheNumbers(string input)
{
var list = new List<string>();
if (string.IsNullOrEmpty(input) != false) return list;
var matches = RegMatch().Matches(input);
matches.Select(m => m.Value).ToList().ForEach(x =>
{
if (decimal.TryParse(x, out var item))
{
list.Add(item.ToString(CultureInfo.CurrentCulture));
}
});
return list;
}
[GeneratedRegex(@"(([\-|\+])?\d*\.?\d+)")]
private static partial Regex RegMatch();
}
@AndreaLanfranchi
Copy link

If I may ... (things always making me mad)

This

 if (foundNumbers.Count <= 0) return;

Logically why check for <= 0 ? Have you ever seen a list with a negative number of items ? Equality to 0 to zero is more than enough.

Then

if (string.IsNullOrEmpty(input) != false) return list;

Why use negation of false when the more straight and readable way is

if (string.IsNullOrEmpty(input) == true) return list;

The return from TryFindTheNumbers is a list of strings which change the input. Not the case of your sample but if we had values in thousands the output would not be what the user entered.

Also joining the strings representing numbers with commas, in many EU cultures is misleading as that is the decimal separator.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment