简体   繁体   English

正则表达式 - 在某些字符串后获取数字

[英]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= 由于数字可能是可变长度的,我想做一个正则表达式,捕获字符串中=符号后的所有内容?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. 有人可以帮我提取最后的数字并将它们放入一个变量中,然后将?order_num=203823之前的?order_num=203823放入其自己的变量中。

I'll post some attempts of my own, but I foresee failure and confusion. 我会发布一些自己的尝试,但我预见到失败和混乱。

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. indexOf使用indexOfsubstring / slice For example: 例如:

var p = s.indexOf("?");
var num = s.substring(p + "?order_num=".length), rest = s.substring(0, p);

I see no need for regex for this: 我认为不需要正则表达式:

var str="aijfoi aodsifj adofija afdoiajd?order_num=3216545";
var n=str.split("?");

n will then be an array, where index 0 is before the ? 那么n将是一个数组,其中索引0在?之前? and index 1 is after. 并且索引1在之后。

Another example: 另一个例子:

var str="aijfoi aodsifj adofija afdoiajd?order_num=3216545";
var n=str.split("?order_num=");

Will give you the result: n[0] = aijfoi aodsifj adofija afdoiajd and n[1] = 3216545 会给你结果: n[0] = aijfoi aodsifj adofija afdoiajdn[1] = 3216545

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. 另外,这将在querystring中的任何一点匹配order_num= ,而不一定只是在查询字符串的最后。

var match = s.substr(s.indexOf('?')).match(/order_num=(\d+)/);
if (match) {
  alert(match[1]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM