Pattern matching to extract multiple numbers within a string

I need help extracting numbers from a string like:

There are 1,000 people in those 3 towns.

I want to create an array like

["1,000", "3"]
.

I found a number matching Regex from Justin in this question

^[+-]?(\d*|\d{1,3}(,\d{3})*)(\.\d+)?\b$

Although it works for checking if it is a number, it needs modification to work on sentences. Specifically, the removal of "start" and "end" markers (^ and $).

See the regex patterns at: regex101 with start/end defined regex101 without start/end defined

Removing the start and end definitions results in unnecessary 0-length matches, but it also splits numbers with commas in them.

How can I modify the regex (or create a new one) to successfully extract numbers from sentences, including those with commas?

An added challenge would be avoiding the occurrence of 0 length matches.

Answer №1

If you're open to considering different groups like 1,00,000 (which is common in some regions), then the expression /-?\d(?:[,\d]*\.\d+|[,\d]*)/g should work for you. I've tried simplifying it further, but it seems that when I attempt to do so, the example "333.33" gets split into "333" and "33" as separate numbers. Using the previous expression keeps it together.

Here's a live example:

const str = "There are 10,000 people in those 3 towns. That's 3,333.33 people per town, roughly. Which is about -67.33 from last year.";
const rex = /-?\d(?:[,\d]*\.\d+|[,\d]*)/g;
let match;
while ((match = rex.exec(str)) !== null) {
    console.log(match[0]);
}

Breaking down /\d(?:[,\d]*\.\d+|[,\d]*)/g:

  • -? - an optional minus sign (x15 pointed this out in their answer!)
  • \d - a digit
  • (?:...|...) - a non-capturing group with an alternation between
    • [,\d]*\.\d+ - zero or more commas and digits followed by a decimal point and one or more digits, e.g., 3,333.33; or
    • [,\d]* - zero or more commas and digits

The first option will match greedily and use the second alternative if there is no decimal point.

Answer №2

To take a different approach, one option is to separate the string by spaces and then check if each part can be converted into a number,

const extractNumbers = str => str.split(/\s+/)
                                .filter(part => part && parseFloat(part.replace(/[.,]/g, '')))


console.log(extractNumbers('There are 1,000 people in those 3 towns. More numbers -23.012 1,00,000,00'))

Answer №3

If you're looking to find both integer and decimal numbers with optional commas in the whole part but not in the decimal part, you can use this regular expression:

/[+-]?(?:(?:\d(?:,(?=\d))?)+(?:\.\d*)?|\.\d+)/

https://regex101.com/r/yOuBPx/1

Although the sample input provided may not cover all boundary conditions handled by this regex, it's best to experiment with different cases to see its full effect.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Bootstrap: enabling the opening of a modal without triggering the collapse feature on the parent element

Here's a simple scenario: I have a Bootstrap 4 table with rows that I would like to be clickable to expand additional hidden rows. The entire tr has data-toggle="collapse". However, within that TR, there are some buttons that I want to open ...

Trouble persisting in loading PopperJS and Bootstrap through RequireJS, despite following the suggested PopperJS version

Struggling to load jquery, popperjs, and bootstrap (v4-beta) using requirejs, I'm consistently encountering this error in the console: Uncaught Error: Bootstrap dropdown require Popper.js (https://popper.js.org) at bootstrap.js:6 at bootstrap ...

Guide on testing code within $(window).on("load", function() {}); with Jasmine

Here is a script written in JavaScript that appends a DIV element to the page on load and then hides it after 3 seconds. var elementHandler = { initialize: function() { var self = this; $(window).on("load", function() { (function ($) ...

From converting Javascript code to PHP and using the innerHTML function for deletion

I'm currently working on implementing a script and could use some assistance with two specific issues that I'm struggling to resolve. The main goal is to enable users to create a running route and then store the route in a database using coordina ...

Using Javascript to apply styling only to the first class element in the document

I am facing a challenge with styling programmatically generated classes and inputs. Here is an example of the structure: <div class="inputHolder"> <input type="button" class="inputclss" value="1"> </ ...

Unable to successfully download npm packages - encountered an error running `[email protected] install: `node-pre-gyp install --fallback-to-build` on Ubuntu 18.04 system

I am facing an issue while trying to npm install (using lerna bootstrap) a project on Ubuntu 18.04. The error I encounter is related to node-pre-gyp install --fallback-to-build. I have attempted installing node-gyp, node-pre-gyp, and apt-get build-essenti ...

Incorporate a prefix into the URL of Angular development servers

When our application is in production, it will not be served from the root. Instead, it will be served from something like https://ourdomain.com/ourapp. This setup is causing problems with image URLs. To work around this issue, I am trying to serve the ap ...

Can components be designed in a way that includes elements such as buttons or text areas in the code, but allows for them to be excluded when the component is used?

I have a custom form component that I designed. Depending on certain cases, I want the form to display either a button or a text field instead of the input field as currently coded. function FormTypeOne(props) { return ( <form className={classes.f ...

Issue with RN-fetch-blob regarding base64 encoding specifically on Android devices

I've encountered an issue in React Native where I'm trying to download a base 64 string from an API and display it as a PDF on mobile devices. The problem arises when using the code on Android, as it returns a 'bad base 64' / invalid P ...

How can CORS be activated? Is it through the server or Javascript, and where does this

Currently, I am testing my ReactJS website on localhost:3333 and my ASP.NET Web API 2 on localhost:54690. I am utilizing axios for my AJAX requests, but encountering an error when making a request. XMLHttpRequest cannot load http://localhost:54690/api/ ...

Is it possible to update labels on an AngularJS slider using a timeout function?

I recently started implementing an AngularJS slider to navigate through various date and time points. Specifically, I am utilizing the draggable range feature demonstrated in this example - https://jsfiddle.net/ValentinH/954eve2L/ The backend provides the ...

"Experience the latest version of DreamFactory - 2.0.4

I'm encountering a 404 error when I send a request to my new DSP. GET http://example.com/api/v2/sericename/_table/tablename 404 (Not Found) Upon checking the Apache error.log, I found this message: ... Got error: PHP message: REST Exception #404 &g ...

Having trouble importing cubing.js into my discord bot running on node

When attempting to import the cubing.js module into my nodejs project for use in a discord.js bot, I encountered an error. The specific import causing issues was const {randomScrambleForEvent } = require('cubing/scramble'), resulting in 'Err ...

What distinguishes event-stream.through from event-stream.map?

After reviewing the documentation on event-stream, it appears that the main distinction between these two methods is whether they operate synchronously or asynchronously. However, I am still unclear on the true significance of this difference. ...

Tips for efficiently passing a JSON object to a resource using AngularJS

I am looking to integrate a web service that accepts a JSON object with two arrays in a POST request and responds with a JSON object array. Now, I want to make a request to this service from my AngularJS application. Below is the code snippet: wellApp.fa ...

An error has occurred in React with a nested JSON object, suggesting that it may actually

I encountered an interesting error with my React file using Axios. While the data retrieval from my post works fine, I am facing a problem when trying to display all posts on one page. Despite my efforts to find a solution, I have not been successful. Bel ...

The jQuery .ajax() GET request is causing issues in Firefox but is functioning properly in Chrome

I am currently utilizing a third-party API to incorporate certain services into an HTML form that I possess. For the API to work, it requires the validation of a hash value and timestamp for each request. These values expire after 30 minutes. To prevent e ...

Create a div element that initially aligns to the left, expands to the full width of the window, and then shrinks back

Hi there! I am currently diving into the world of javascript and jQuery, with a specific goal in mind. I want to create functionality where a div expands to the width of the window when clicked, then shrinks back down to its original size but switches alig ...

What could be causing the misalignment between the desired output and the response from the AJAX request

Below is a basic JavaScript file I am working with: $.ajax({ url: "is_complete.php", type: "post", success: function (data) { if(data == 1) { } alert("ok") } }) The message "ok" will only be di ...

Encountering a "dependency resolution error" while deploying a React application with Parcel on Heroku

I've developed a compact application and I'm in the process of deploying it to Heroku. However, I keep encountering an error stating: '@emotion/is-prop-valid' dependency cannot be resolved. It's worth mentioning that this project d ...