Javascript 如何选择字符串中的最后一个数字?

Javascript 如何选择字符串中的最后一个数字?,javascript,jquery,regex,Javascript,Jquery,Regex,我有这样一个字符串: 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"; {spaces in here doesn't matter}{any digit}{do

我有这样一个字符串:

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";
{spaces in here doesn't matter}{any digit}{dot}{every thing in here til end of line}
我想要
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";
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";
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
会破坏该序列


如你所见,我想要最后一个数字,它是列表样式。像这样:

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";
{spaces in here doesn't matter}{any digit}{dot}{every thing in here til end of line}

我该怎么做呢?

这应该和跑步一样简单

(string.match(/[0-9]+/gm) || []).pop()
这将在多行字符串中搜索数字,并获取最后一个数字。如果没有找到数字,它将返回一个空数组,该数组将返回
pop()
undefined
。听起来正是你需要的

试试这个模式

^[\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

为什么第二个示例
null
?整个字符串中的最后一个数字(不能像你在文章中那样包含换行符)是
2
,除非我遗漏了什么。是否要字符串最后一行的数字?@ScottKaye我编辑了我的问题。@winhowes
/^\s*\n?\d.$/gm
。。但它并不完整。。!嗯,我不确定。。!您的正则表达式匹配所有数字。。!这不符合我的模式。什么是
pop()
?那么,什么返回您的正则表达式呢?我不明白anything@stack,您要求的
null
!因为两个连续的
\n
啊,我现在拿到了。。!但是当我删除其中一个
\n
时,所有这些都将被选中。。!但是我需要在所选内容中只获得最后一个
2
。我明白了,(你在小提琴中写了
$0
,而不是
$1
)。好吧,不知怎么的,这很好。。但是它有一个小问题,请看一下,它返回
5
。但我需要的是,捕获组只需选择换行符开头的每个数字,然后是一个点。@stack,上面的解释