質問

So I read a few others but still couldn't get it to work. (call me stupid if you'd like) Anyways, what I'm basically trying to achieve is to have it read all numbers behind a specific match.

Let's say I'm trying to find the numbers after the word 'numberOfApples 3531053' - I want it to recognize if the word numberOfApples is in an variable, then be able to read the amount/numbers after.

I'll write out an example below:

var str = "asd asd numberOfApples 125912592 aspdla";
var apples = /numberOfApples/;
if(apples.test(str)) {
   console.log(str);
}

Now this would print out 'numberOfApples', but I want it to check the numbers behind it and put them into an variable or array. As a whole variable, not each number in their own.

I really have no clue so, if anyone can help me I'd appreciate it! Thanks.

役に立ちましたか?

解決

How about;

var str = "asd asd numberOfApples 125912592 aspdla";
var apples = "numberOfApples";

var re = new RegExp(apples + "\\s*(\\d+)");
var m = str.match(re);

if (m != null)
{
    console.log(m[1]);
}    

他のヒント

var regex = /numberOfApples\s(\d+)/

This catches the digits after the word (if there is a whitespace character after the word)

var match = regex.exec(str);
console.log(match[1]);
var res = /numberOfApples (\d+)/.exec("asd asd numberOfApples 125912592 aspdla");
res = (res !== null) ? res[1] : null;
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top