3

I'm trying to write a regex in javascript to match a series of numbers after a particular string without getting the string in result. So far, I have come up with this:

(?!smart_id=)[0-9]+

which is to be tested against strings like:

ksld8403smart_id=9034&kqwop
discid=783&smartid=83234&ansqw
fdsjfnfd3209sdf&smart_id=2102&hjg

but I'm getting both the numbers before and after smart_id. The tests need to be performed on https://regexr.com/

Mirhawk
  • 205
  • 1
  • 3
  • 14
  • This looks like a query parameter string. It would be much easier and less error prone to use a library function or an inbuilt language function to extract these values. – ssc-hrep3 Nov 21 '17 at 07:47
  • https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript – ssc-hrep3 Nov 21 '17 at 07:51
  • 1
    Lookbehind is not a standard feature in JS RegExp as of now, `/(?<=smart_id=)[0-9]+/.exec("smart_id=232134")[0]` in my Chrome console shows `"232134"`, but to make it compatible with other browsers and versions, you need to use `/smart_id=(\d+)/.exec(str)[1]`. So, at regexr, you will never be able to discard a part of the match on the left (until it supports the new JS regex syntax). – Wiktor Stribiżew Nov 21 '17 at 09:57

1 Answers1

0

You can use regex along with array#map. Once you have matched result, you can array#split the result on = and get the value at the first index.

var str = `ksld8403smart_id=9034&kqwop
discid=783&smartid=83234&ansqw
fdsjfnfd3209sdf&smart_id=2102&hjg`;

console.log(str.match(/(smart_id=)(\d+)/g).map(matched => +matched.split('=')[1]));
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51