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
*/