简体   繁体   English

使用regex / javascript提取姓氏

[英]Extracting last word using regex/javascript

This is for the use case of input line which is rather short (on purpose). 这是针对输入线的使用情况,该输入线很短(故意)。 It supposed to autosend message when the input is full but keep last word in place. 它应该在输入已满时自动发送消息,但保留最后一个单词。

I am looking for regex that would fulfill these scenarios: 我正在寻找能够满足以下情况的正则表达式:

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 "

So far I came up with these variants: 到目前为止,我想出了以下变体:

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

I am not sure how to fulfill all scenarios. 我不确定如何实现所有方案。 Is it even possible ? 可能吗?

You can use this String#match : 您可以使用以下String#match

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

And use group #2 and group #3 in the resulting array. 并在结果数组中使用组2和组3。 (using m[1] and m[2] ) (使用m[1]m[2]

Online Regex Demo 在线正则表达式演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM