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

标签 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";

我想要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})

Demo

数字后面必须有一个点

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

关于javascript - 如何选择字符串中的最后一个数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34972273/

相关文章:

javascript - this.props.function() 在 React 应用程序中未定义?

javascript - 谷歌 Material 图表(散点图)不显示趋势线或工具提示

javascript - 根据 URL 将正文类添加到页面列表

javascript - 如何使用 jQuery 将值与 JSON 对象中的名称进行匹配?

regex - 正则表达式单词边界,不包括连字符

javascript - 使用 Google Closure 从 LabelInput 访问数据

javascript - Yii - CHtml::ajaxLink - TypeError:设置未定义

jquery - 列中的 Bootstrap 导航栏 - 到达页面顶部时已修复?

php - 尝试使用 PHP 正则表达式生成 url slugs,日文字符不通过

python - 组合多个正则表达式替换