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,239 questions

56,142 answers

573 users

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

1 Answer

0 votes
import Foundation

// Pre-compiled regular expression matching standalone numbers with an explicit decimal point.
// \b establishes word boundaries; \d+\.\d+ requires digits before and after the dot.
private let floatRegex: NSRegularExpression? = {
    let pattern = #"\b\d+\.\d+\b"#
    return try? NSRegularExpression(pattern: pattern, options: [])
}()

/// Extracts all double-precision floating-point numbers containing an explicit
/// decimal point from an input string.
///
/// - Parameter input: Source text containing mixed words and numerical tokens.
/// - Returns: An array of parsed `Double` values.
func extractFloats(from input: String) -> [Double] {
    guard let regex = floatRegex, !input.isEmpty else {
        return []
    }

    let range = NSRange(input.startIndex..., in: input)
    let matches = regex.matches(in: input, options: [], range: range)

    // Transform NSRange matches directly into Double values.
    // compactMap filters out nil values automatically if string slice parsing fails.
    return matches.compactMap { match in
        guard let substringRange = Range(match.range, in: input) else {
            return nil
        }
        let token = String(input[substringRange])
        return Double(token)
    }
}

// Main program execution
func main() {
    let s = "c/c++ c# go 893725.1045 java python 3.14 php 0.0076 javascript"

    let numbers = extractFloats(from: s)

    print("Extracted floating-point numbers:")
    for number in numbers {
        print(number)
    }
}

main()


/*
run:

Extracted floating-point numbers:
893725.1045
3.14
0.0076

*/

 



answered 3 days ago by avibootz

Related questions

...