Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regex to match first two numbers in a string?

I have a string of this format:

words 9999 words words words 1234 words words words words 3333...

The words and numbers are unknown. Additionally, a the number of words and numbers and their order is unknown. So this is also fine:

words words words 9999 words words words words words words 1234 words 9934 4945 6945...

I want to match only the first two numbers in the string. What regex can do this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Edit: I cannot just select the first two numbers, as there can be a tremendous amount, and it is a huge waste of time to match all of them. In particular, my testing string has over 16,000 numbers.

>Solution :

You can use \d+ twice to achieve this.

const string = "words 9999 words words words 1234 words words words words 3333";
const pattern = /^\D*(\d+)\D*(\d+)/;
const match = string.match(pattern);

if (match) {
    const firstNumber = match[1];
    const secondNumber = match[2];
    console.log(firstNumber, secondNumber);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading