Multitut
Multitut

Reputation: 2169

Javascript - Regular expression for getting a number inside a alphanumerical string?

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

Answers (4)

hwnd
hwnd

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 splitting the string?

var r = '*#13**67*124##'.split(/[*#]+/).filter(Boolean).pop()
console.log(r); // => "124"

Upvotes: 3

Federico Piazza
Federico Piazza

Reputation: 31035

This is a nice example for use regex lookahead.

You can use this regex:

\d+(?=##)

Working demo

Upvotes: 2

GregL
GregL

Reputation: 38151

function getValue(string) {
    return parseInt(string.replace(/^.*(\d+)##$/gi, "$1"), 10);
}

Upvotes: 2

celeritas
celeritas

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

Related Questions