这是针对输入线相当短(故意)的用例。当输入已满时,它应该自动发送消息,但保留最后一个单词。
我正在寻找能够满足这些场景的正则表达式:
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
我不确定如何满足所有场景。这可能吗?
最佳答案
您可以使用此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
关于javascript - 使用正则表达式/javascript 提取最后一个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24778395/