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

1 Answer

0 votes
/**
 * Extracts all double-precision floating-point numbers containing explicit
 * decimal points from a given input string.
 *
 * @param input - Source text containing mixed text and numeric tokens.
 * @returns An array of parsed floating-point numbers.
 */
function extractFloats(input: string): number[] {
  if (!input || input.trim() === "") {
    return [];
  }

  // Regular expression matching standalone numbers containing an explicit decimal point.
  // \b ensures word boundary alignment; \d+\.\d+ requires digits before and after the dot.
  const floatPattern: RegExp = /\b\d+\.\d+\b/g;

  // String.prototype.matchAll returns a lazy iterator of Match objects.
  
  // Array.from builds the output array while converting 
  // string matches to primitive numbers in one pass.
  const matches: IterableIterator<RegExpMatchArray> = input.matchAll(floatPattern);
  
  return Array.from(matches, (match: RegExpMatchArray): number => Number(match[0]));
}

/**
 * Main execution function demonstrating usage.
 */
function main(): void {
  // Example input string with explicit type annotation
  const s: string = "c/c++ c# go 893725.1045 java python 3.14 php 0.0076 javascript";

  const floatNumbers: number[] = extractFloats(s);

  console.log("Extracted floating-point numbers:");
  for (const num of floatNumbers) {
    console.log(num);
  }
}

main();


/*
run:

Extracted floating-point numbers:
893725.1045
3.14
0.0076

*/

 



answered Sep 17 by avibootz

Related questions

...