Greggy
Greggy

Reputation: 719

Regex to extract two numbers with spaces from string

I have problem with simple rexex. I have example strings like:

Something1\sth2\n649 sth\n670 sth x
Sth1\n\something2\n42 036 sth\n42 896 sth y

I want to extract these numbers from strings. So From first example I need two groups: 649 and 670. From second example: 42 036 and 42 896. Then I will remove space.

Currently I have something like this:

\d+ ?\d+

But it is not a good solution.

Upvotes: 1

Views: 1534

Answers (3)

Morphyish
Morphyish

Reputation: 4062

If you need to remove the spaces. Then the easiest way for you to do this would be to remove the spaces and then scrape the numbers using 2 different regex.

str.replace(/\s+/, '').match(/\\n(\d+)/g)

First you remove spaces using the \s token with a + quantifier using replace.

Then you capture the numbers using \\n(\d+).

The first part of the regex helps us make sure we are not capturing numbers that are not following a new line, using \ to escape the \ from \n.

The second part (\d+) is the actual match group.

Upvotes: 1

emonn
emonn

Reputation: 56

var str1 = "Something1\sth2\n649 sth\n670 sth x";
var str2 = "Sth1\n\something2\n42 036 sth\n42 896 sth y";
var reg = /(?<=\n)(\d+)(?: (\d+))?/g;
var d;
while(d = reg.exec(str1)){
    console.log(d[2] ? d[1]+d[2] : d[1]);
}
console.log("****************************");
while(d = reg.exec(str2)){
    console.log(d[2] ? d[1]+d[2] : d[1]);
}

Upvotes: 0

Code Maniac
Code Maniac

Reputation: 37755

You can use

\n\d+(?: \d+)?
  • \n - Match new line
  • \d+ - Match digit from 0 to 9 one or more time
  • (?: \d+)? - Match space followed by digit one or more time. ( ? makes it optional )

let strs = ["Something1\sth2\n649 sth\n670 sth x","Sth1\n\something2\n42 036 sth\n42 896 sth y"]

let extractNumbers = str => {
  return str.match(/\n\d+(?: \d+)?/g).map(m => m.replace(/\s+/g,''))
}

strs.forEach(str=> console.log(extractNumbers(str)))

Upvotes: 2

Related Questions