使用正则表达式/ javascript提取最后一个单词

时间:2014-07-16 10:24:22

标签: javascript regex

这是针对输入行的用例,它是相当短的(故意)。它应该在输入已满时自动发送消息,但保留最后一个字。

我正在寻找能够满足这些情况的正则表达式:

input: "testing"
output: [1] - "testing"; [2] - null

input: "testing testing"
output: [1] - "testing"; [2] - "testing"

input: "testing testing testing"
output: [1] - "testing testing"; [2] - "testing"

input: "testing testing testing "
output: [1] - "testing testing"; [2] - "testing "

到目前为止,我想出了这些变体:

/(.*)\s+(\w+)/ - closest solution, but doesn't match for one word without spaces
/(.*)(?:\s+(\w+))?/ - is not recognizing last word

我不确定如何实现所有方案。它甚至可能吗?

1 个答案:

答案 0 :(得分:2)

您可以使用此String#match

var input = 'testing1 testing2 testing3 ';
var m = input.match(/^(.+?)(?: +(\w+\ *))?$/);
// ["testing1 testing2 testing3 ", "testing1", "testing2 testing3 "]

在结果数组中使用组#2和组#3。 (使用m[1]m[2]

Online Regex Demo