简体   繁体   中英

New to JavaScript RegEx - Selecting Middle Word from Three-Word String

I am very new to JavaScript's RegExp library, and need help selecting the middle word from a three-word string.
For example: Saturday October 1 would return October .

My (feeble) attempt was \\s.*\\s , but this returned (space)October(space) . However, I need the spaces to be omitted from the match.

Any help is appreciated!

Thanks

You could simply use a capturing group and then refer to group index #1 for the match result.

var r = 'Saturday October 1'.match(/\s(.*)\s/);
if (r)
    console.log(r[1]); //=> "October"

Or as stated in the comments, trim the match result.

var r = 'Saturday October 1'.match(/\s.*\s/);
if (r)
    console.log(r[0].trim()); //=> "October"

But wouldn't split ting the string be easier in this case?

var r = 'Saturday October 1'.split(' ')[1];
console.log(r); //=> "October"

I think the easiest solution is to trim the returned value or

var match = 'Saturday October 1'.match(/\s(.*)\s/); 
var text = match && match[1]

使用第一个匹配组来精确地包含中间词

\s+(\b.*)\s+
^.*?\s(\w+)

Try this.Grab the capture.See demo.

http://regex101.com/r/hQ1rP0/44

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