Reputation: 2169
so I am looking to get an specific numerical value using Javascript and regular expressions from a string like this: *#13**67*value##
So from
*#13**67*2##
*#13**67*124##
*#13**67*1##
I need to get 2, 124 and 1. Any help will be really appreciated. Thanks!
Upvotes: 0
Views: 54
Reputation: 70750
If your strings are always in this format, match the digits at the end of the string.
var r = '*#13**67*124##'.match(/\d+(?=#+$)/);
if (r)
console.log(r[0]); // => "124"
Multi-line matching:
var s = '*#13**67*2##\n*#13**67*124##\n*#13**67*1##',
r = s.match(/\d+(?=#+$)/gm)
console.log(r); // => [ '2', '124', '1' ]
Perhaps split
ting the string?
var r = '*#13**67*124##'.split(/[*#]+/).filter(Boolean).pop()
console.log(r); // => "124"
Upvotes: 3
Reputation: 31035
This is a nice example for use regex lookahead.
You can use this regex:
\d+(?=##)
Upvotes: 2
Reputation: 38151
function getValue(string) {
return parseInt(string.replace(/^.*(\d+)##$/gi, "$1"), 10);
}
Upvotes: 2
Reputation: 2281
How about this:
var regex = /^\*\#\d{2}\*{2}\d{2}\*(\d+)\#{2}$/;
var value = '*#13**67*124##'.match(regex)[1]; // value will be 124
Upvotes: 1