Javascript 正则表达式从字符串的末尾获取数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6340180/
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 to get the number from the end of a string
提问by Saurabh Kumar
i have a id like stringNumber variable like the one as follows : example12 I need some javascript regex to extract 12 from the string."example" will be constant for all id and just the number will be different.
我有一个像 stringNumber 这样的 id 变量,如下所示:example12 我需要一些 javascript 正则表达式来从字符串中提取 12。“example”对于所有 id 都是常量,只是数字会有所不同。
回答by alex
This regular expression matches numbers at the end of the string.
此正则表达式匹配字符串末尾的数字。
var matches = str.match(/\d+$/);
It will return an Array
with its 0
th element the match, if successful. Otherwise, it will return null
.
如果成功,它将返回Array
带有第0
th 个元素的匹配项。否则,它将返回null
。
Before accessing the 0
member, ensure the match was made.
在访问0
成员之前,请确保已进行匹配。
if (matches) {
number = matches[0];
}
If you must have it as a Number
, you can use a function to convert it, such as parseInt()
.
如果必须将其作为 . Number
,则可以使用函数将其转换,例如parseInt()
.
number = parseInt(number, 10);
回答by jensgram
RegEx:
正则表达式:
var str = "example12";
parseInt(str.match(/\d+$/)[0], 10);
String manipulation:
字符串操作:
var str = "example12",
prefix = "example";
parseInt(str.substring(prefix.length), 10);