Created
May 14, 2024 13:49
-
-
Save karenpayneoregon/4c6beda00f31104c591d643808dfe656 to your computer and use it in GitHub Desktop.
Get numbers values from string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If I may ... (things always making me mad)
This
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
Why use negation of false when the more straight and readable way is
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.