Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex - get numbers after certain character string

I have a text string that can be any number of characters that I would like to attach an order number to the end. Then I can pluck off the order number when I need to use it again. Since there's a possibility that the number is variable length, I would like to do a regular expression that catch's everything after the = sign in the string ?order_num=

So the whole string would be

"aijfoi aodsifj adofija afdoiajd?order_num=3216545"

I've tried to use the online regular expression generator but with no luck. Can someone please help me with extracting the number on the end and putting them into a variable and something to put what comes before the ?order_num=203823 into its own variable.

I'll post some attempts of my own, but I foresee failure and confusion.

like image 461
1252748 Avatar asked Jun 04 '12 22:06

1252748


2 Answers

var s = "aijfoi aodsifj adofija afdoiajd?order_num=3216545";

var m = s.match(/([^\?]*)\?order_num=(\d*)/);
var num = m[2], rest = m[1];

But remember that regular expressions are slow. Use indexOf and substring/slice when you can. For example:

var p = s.indexOf("?");
var num = s.substring(p + "?order_num=".length), rest = s.substring(0, p);
like image 79
MaxArt Avatar answered Nov 15 '22 22:11

MaxArt


You can substring from the first instance of ? onward, and then regex to get rid of most of the complexities in the expression, and improve performance (which is probably negligible anyway and not something to worry about unless you are doing this over thousands of iterations). in addition, this will match order_num= at any point within the querystring, not necessarily just at the very end of the querystring.

var match = s.substr(s.indexOf('?')).match(/order_num=(\d+)/);
if (match) {
  alert(match[1]);
}
like image 31
Ben Taber Avatar answered Nov 15 '22 23:11

Ben Taber