如何选择字符串中的最后一个数字?
问题描述:
我有一个这样的字符串:如何选择字符串中的最后一个数字?
var str = "this is test
1. this is test
2. this is test
3. this is test
this is test
1. this test
2. this is test";
我想2
。
又如:
var str = "this is test
1. this is test
2. this is test
3. this is test
this is test
1. this test
2. this is test
this is test";
我想2
。
又如:
var str = "this is test
1. this is test
2. this is test
3. this is test
this is test
1. this test
2. this is test
this is test";
我想null
,因为连续两个\n
中断该序列。
正如你看到的,我想最后的数字是列表样式。像这样:
{spaces in here doesn't matter}{any digit}{dot}{every thing in here til end of line}
我该怎么做?
答
尝试这种模式
^[\s\S]*(?:^|\r?\n)\s+(\d+)(?![\s\S]*(\r?\n){2})
一个强制性点的数量使用后什么
^[\s\S]*(?:^|\r?\n)\s+(\d+)\.(?![\s\S]*(\r?\n){2})
解释:
^[\s\S]* # from the beginning "^" consume everything
(?:^|\r?\n) # if not first line then followed by a newline
\s* # followed by white spaces
(\d+) # capturing group to get your number
(?! # a negative look-ahead
[\s\S]*(\r?\n){2} # anything followed by {2} new lines
) # end of negative look-ahead
答
这应该是那么容易,因为只是运行
(string.match(/[0-9]+/gm) || []).pop()
这个搜索在多行字符串的数量和需要的最后一个。如果没有找到数字,则返回空数组,该数组将返回undefined
,pop()
。听起来正是你所需要
+0
恩,我不确定..!你的正则表达式匹配每个数字..!它不符合我的模式。 'pop()'是什么? – stack
为什么是第二个'null'的例子吗?整个字符串中的最后一个数字(不能包含他们在帖子中的换行符)是'2',除非我错过了某些东西。你想在字符串的最后一行的数字? – Scott
@ScottKaye我编辑了我的问题。 – stack
@winhowes'/^\ s * \ n?\ d。* $/gm' ..但它不完整..! – stack