这是针对输入行的用例,它是相当短的(故意)。它应该在输入已满时自动发送消息,但保留最后一个字。
我正在寻找能够满足这些情况的正则表达式:
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
我不确定如何实现所有方案。它甚至可能吗?
答案 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]
)