Ælex
Ælex

Reputation: 14829

JavaScript regex get number after string

After coming to the shocking realization that regular expressions in JavaScript are somewhat different from the ones in PCE, I am stuck with the following.

In php I extract a number after x:

(?x)[0-9]+

In JavaScript the same regex doesn't work, due to invalid group resulting from the capturing parenthesis difference.

So I am trying to achieve the same trivial functionality, but I keep getting both the x and the number:

(?:x)([0-9]+)

How do I capture the number after x without including x?

Upvotes: 5

Views: 11344

Answers (5)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626690

How do I capture the number after x without including x?

In fact, you just want to extract a sequence of digits after a fixed string/known pattern.

Your PCRE (PHP) regex, (?x)[0-9]+, is wrong becaue (?x) is an inline version of a PCRE_EXTENDED VERBOSE/COMMENTS flag (see "Pattern Modifiers"). It does not do anything meaningful in this case, (?x)[0-9]+ is equal to [0-9]+ or \d+.

You can use

console.log("x15 x25".match(/(?<=x)\d+/g));

You can also use a capturing group and then extract Group 1 value after a match is obtained:

const match = /x(\d+)/.exec("x15");
if (match) {
  console.log(match[1]); // Getting the first match
}

// All matches
const matches = Array.from("x15,x25".matchAll(/x(\d+)/g), x=>x[1]);
console.log(matches);

Upvotes: 3

jimplode
jimplode

Reputation: 3502

You can try the following regex: (?!x)[0-9]+

fiddle here: https://jsfiddle.net/xy6x938e/1/

This is assuming that you are now looking for an x followed by a number, it uses a capture group to capture just the numbers section.

var myString = "x12345";
var myRegexp = /x([0-9]+)/g;
var match = myRegexp.exec(myString);
var myString2 = "z12345";
var match2 = myRegexp.exec(myString2);

if(match != null && match.length > 1){
    alert('match1:' + match[1]);
}
else{
    alert('no match 1');
}
if(match2 != null && match2.length > 1){
    alert('match2:' + match2[1]);
}
else{
    alert('no match 2');
}

Upvotes: 4

nilfalse
nilfalse

Reputation: 2419

You still can use exclusive pattern (?!...)

So, for your example it will be /(?!x)[0-9]+/. Give a try to the following:

/(?!x)\d+/.exec('x123')
// => ["123"]

Upvotes: 0

lino
lino

Reputation: 190

(\d+) try this! i have tested on this tool with x12345 http://www.regular-expressions.info/javascriptexample.html

Upvotes: 2

Jodevan
Jodevan

Reputation: 750

This works too:

/(?:x)([0-9]+)/.test('YOUR_STRING');

Then, the value you want is:

RegExp.$1 // group 1

Upvotes: 4

Related Questions