简体   繁体   English

正则表达式从字符串中检索数字

[英]Regex to retrieve numbers from string

I have this string: 我有这个字符串:

var string = "look1_slide2"; var string =“ look1_slide2”;

I would like to extract the the look number ie 1 and the slide ie 2 and save them in two different variables, I guess I could do it with a Regex but not sure how. 我想提取外观编号(即1和幻灯片(即2并将它们保存在两个不同的变量中,我想我可以使用Regex来做到这一点,但不确定如何做到。 Any help? 有什么帮助吗? The string will always have that format btw 该字符串将始终具有该格式btw

Thanks! 谢谢!

Since your string is always in that format you can simply read second and third entries of the returned regex matches array : 由于您的字符串始终采用这种格式,因此您只需读取返回的正则表达式匹配数组的第二和第三项即可:

var string = 'look1_slide2';
var regex = /look(\d)_slide(\d)/g;

matches = regex.exec(string);
console.log(matches[1]);
console.log(matches[2]);

See RegExp.exec() doc 请参阅RegExp.exec()文档

var txt = "#div-name-1234-characteristic:561613213213";
var numb = txt.match(/\d/g);
numb = numb.join("");
alert (numb);​

This will print 1234561613213213 这将打印1234561613213213

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

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