给出以下句子:Crazy Fredrick bought many very exquisite opal jewels.
,什么正则表达式允许我过滤掉每个其他单词?我正在做这样的替换:
"Crazy Fredrick bought many very exquisite opal jewels.".replace(/regex goes here/gi, "replace string goes here")
所以我想创建一个正则表达式,将该句子转换为Fredrick many exquisite jewels.
或crazy bought very opal
。
答案 0 :(得分:2)
可以使用以下内容(假设您的单词都与\ w匹配)
"Crazy Fredrick bought many very exquisite opal jewels.".replace(/(\w+) (\w+)/g, '$1');
-> "Crazy bought very opal."
用2美元取代1美元可以获得:
"Fredrick many exquisite jewels."
答案 1 :(得分:1)
不确定RegEx是否是正确的工具,但您可以将split
字符串按空格分成数组,然后使用filter
删除奇数或偶数元素:
var s = "Crazy Fredrick brought many very exquisite opal jewels";
s.split(/\s+/)
.filter(function (_, index) {
return index % 2 !== 0; // only want "odd" words
}).join(" ");
// yields "Fredrick many exquisite jewels"
答案 2 :(得分:0)
不是最佳解决方案,但您可以尝试使用这些正则表达式:
\b\S+\b\s?(?=((\b\S+\b\s?){2})*\.?$)
\b\S+\b\s?(?=\b\S+\b\s?((\b\S+\b\s?){2})*\.?$)
此处的解释和演示:http://regex101.com/r/kR3hS5