Skip to content Skip to sidebar Skip to footer

Regular Expression: Match Whole Numbers In String

I'm trying to match numbers using JavaScript in a string with the following format: NUM;#username;#NUM;#username so for example, in the following string: 252;#Lemmywinks07;#27;#T

Solution 1:

If Usernames Do Not Have Numbers In Them...

To find matches, you'll actually want to use the match() function as opposed to exec() :

var input = '252;#Lemmywinks;#27;#Trogdor';
var output = input.match(/\d+/g); // yields ['252', '27'];

If Usernames Do Have Numbers In Them...

Alternatively, you could split your existing string into individual components using the ; and # characters via the split() function and test each section accordingly :

var input = '252;#Lemmywinks2;#27;#Trogdor';
var output = input.split(/[;#]/).filter(function(x){ return (/^\d+$/g).test(x); }); 

Solution 2:

Don't use exec but match when you want to get all matches:

"252;#Lemmywinks;#27;#Trogdor".match(/\d+/g);

exec is meant to be used iteratively, you would have to loop until there's no more result, while match immediately gives you an array.

To only take numbers that are full fields, I wouldn't use a regex here, I would have just split:

"252;#Lemmywinks;#27;#Trogdor".split(";#").map(Number).filter(v=>v===v)

(note that this solution also gives you directly numbers instead of strings)

Solution 3:

You could match the whole line and retrieve the appropriate groups with the following regex :

var linePattern = /(\d+);[^;]*;#(\d+);[^;]*/

Then data.match(linePattern)[1] would return the first number, data.match(linePattern)[2] the second number and data.match(linePattern)[0] the whole line.

While this approach is heavier than matching numbers in the line or splitting around the delimiter, it has the advantage of checking if a line respects the expected pattern and avoids returning incoherent results for anomalous entries.

Post a Comment for "Regular Expression: Match Whole Numbers In String"