Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,181 questions

56,073 answers

573 users

How to extract all floating-point numbers from a string of words in C#

1 Answer

0 votes
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text.RegularExpressions;

public class Program
{
    // Static compiled Regex instance compatible with standard Mono C#.
    // Matches standalone floating-point numbers containing an explicit decimal point.
    private static readonly Regex FloatRegex = new Regex(@"\b\d+\.\d+\b", RegexOptions.Compiled | RegexOptions.ExplicitCapture);

    /// <summary>
    /// Extracts all double-precision floating-point numbers containing a decimal point from an input string.
    /// </summary>
    /// <param name="input">Source text containing mixed words and numerical values.</param>
    /// <returns>A list of successfully parsed double values.</returns>
    public static List<double> ExtractFloats(string input)
    {
        List<double> results = new List<double>();

        if (string.IsNullOrEmpty(input)) {
            return results;
        }

        // Scan the string for regex matches
        MatchCollection matches = FloatRegex.Matches(input);

        foreach (Match match in matches) {
            double parsedValue;

            // Use CultureInfo.InvariantCulture to guarantee '.' is treated as decimal separator across all locales
            if (double.TryParse(match.Value, NumberStyles.Float, CultureInfo.InvariantCulture, out parsedValue))
            {
                results.Add(parsedValue);
            }
        }

        return results;
    }

    public static void Main(string[] args)
    {
        string s = "c/c++ c# go 893725.1045 java python 3.14 php 0.0076 javascript";

        List<double> extractedNumbers = ExtractFloats(s);

        Console.WriteLine("Extracted floating-point numbers:");
        foreach (double number in extractedNumbers) {
            // Print using InvariantCulture to ensure dot formatting
            Console.WriteLine(number.ToString(CultureInfo.InvariantCulture));
        }
    }
}


/*
run:

Extracted floating-point numbers:
893725.1045
3.14
0.0076

*/

 



answered 7 hours ago by avibootz

Related questions

...