cronicryo
cronicryo

Reputation: 437

Find numbers in a string not preceded or followed by any letters in javascript

im not all that familiar with regular expressions. im trying to figure out how to find a number in a string that is not preceded or followed by a letter with javascript

s= "sc010sc"
//shouldnt return 

s = "x0001"
//shouldnt return 

s = "thing_0001_5642"
//return [0001, 5642]



s = "05012"
//return 05012

Upvotes: 0

Views: 880

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626826

You can use

var rx = /(?:^|[^a-z0-9])(\d+)(?![0-9a-z])/ig;
var s = "thing_0001_5642";// with "sc010sc" it does not return any result
var res = [];
while((m=rx.exec(s)) !== null) {
	res.push(m[1]);
}
console.log(res);

Pattern details:

  • (?:^|[^a-z0-9]) - either start of string or non-digit and non-letter
  • (\d+) - Group 1 capturing 1 or more digits
  • (?![0-9a-z]) - that are not followed with a digit or letter.

Since the /i modifier is used, all ASCII letters are matched with [a-z].

As we need to access captured values, I am using a RegExp#exec in a loop to only grab match[1] value.

Upvotes: 2

Related Questions