javascript 使用正则表达式从字符串中提取数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11397403/
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
Extracting numbers from a string using regular expressions
提问by Olivier
I am clueless about regular expressions, but I know that they're the right tool for what I'm trying to do here: I'm trying to extract a numerical value from a string like this one:
我对正则表达式一无所知,但我知道它们是我在这里尝试做的事情的正确工具:我正在尝试从这样的字符串中提取数值:
approval=not requested^assignment_group=12345678901234567890123456789012^category=Test^contact_type=phone^
Ideally, I'd extract the following from it: 12345678901234567890123456789012
None of the regexes I've tried have worked. How can I get the value I want from this string?
理想情况下,我会从中提取以下内容:12345678901234567890123456789012
我尝试过的所有正则表达式都不起作用。我怎样才能从这个字符串中得到我想要的值?
回答by elclanrs
This will get all the numbers:
这将获得所有数字:
var myValue = /\d+/.exec(myString)
回答by Graham
mystr.match(/assignment_group=([^\^]+)/)[1]; //=> "12345678901234567890123456789012"
This will find everything from the end of "assignment_group=" up to the next caret ^
symbol.
这将找到从“assignment_group=”结尾到下一个插入^
符号的所有内容。
回答by Rocket Hazmat
Try something like this:
尝试这样的事情:
/\^assignment_group=(\d*)\^/
This will get the number for assignment_group
.
这将获得assignment_group
.
var str = 'approval=not requested^assignment_group=12345678901234567890123456789012^category=Test^contact_type=phone^',
regex = /\^assignment_group=(\d*)\^/,
matches = str.match(regex),
id = matches !== null ? matches[1] : '';
console.log(id);
回答by Phillip Schmidt
If there is no chance of there being numbers anywhere but when you need them, you could just do:
如果在任何地方都没有数字,但是当你需要它们时,你可以这样做:
\d+
the \d matches digits, and the + says "match any number of whatever this follows"
\d 匹配数字,+ 表示“匹配后面的任意数量”