Javascript regex - 获取特定字符串后的数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10889391/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
regex - get numbers after certain character string
提问by 1252748
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
放入自己的变量中。
I'll post some attempts of my own, but I foresee failure and confusion.
我会发布一些我自己的尝试,但我预见到失败和混乱。
回答by MaxArt
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:
但请记住,正则表达式很慢。尽可能使用indexOf
和substring
/ slice
。例如:
var p = s.indexOf("?");
var num = s.substring(p + "?order_num=".length), rest = s.substring(0, p);
回答by Simon Forsberg
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 ? and index 1 is after.
n
然后将是一个数组,其中索引 0 在 ? 和索引 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 afdoiajd
和
n[1]
=3216545
回答by Ben Taber
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.
您可以从第一个实例?
开始使用子字符串,然后使用正则表达式来消除表达式中的大部分复杂性,并提高性能(这可能可以忽略不计,除非您在数千次迭代中这样做,否则无需担心) . 此外,这将匹配order_num=
查询字符串内的任何点,不一定只在查询字符串的最后。
var match = s.substr(s.indexOf('?')).match(/order_num=(\d+)/);
if (match) {
alert(match[1]);
}