简体   繁体   English

JavaScript RegEx的新功能-从三字串中选择中间字

[英]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. 我是JavaScript的RegExp库的新手,需要帮助从三个单词的字符串中选择中间单词。
For example: Saturday October 1 would return October . 例如: Saturday October 1 October Saturday October 1将返回October

My (feeble) attempt was \\s.*\\s , but this returned (space)October(space) . 我的(尝试)尝试是\\s.*\\s ,但是返回了(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. 您可以简单地使用捕获组 ,然后参考组索引#1获取匹配结果。

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? 但是在这种情况下split字符串会不会更容易?

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 http://regex101.com/r/hQ1rP0/44

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

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