简体   繁体   中英

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 :

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. (using m[1] and m[2] )

Online Regex Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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