简体   繁体   English

JavaScript 正则表达式用于隔离单词/拆分单词

[英]JavaScript Regex for isolating words / splitting around words

I'm trying to separate multiple words in a string, without removing anything, and form them into an array.我试图在一个字符串中分隔多个单词,而不删除任何内容,并将它们形成一个数组。 I'm using the.split method but can't find the exact pattern for multiple words and including spaces.我正在使用 .split 方法,但找不到多个单词和包括空格的确切模式。

my string is:我的字符串是:

const testSentence = 'a foxy dog met a dogged fox';

I want to split it at the words 'dog' and 'fox', so I get the array:我想将它拆分为“狗”和“狐狸”这两个词,所以我得到了数组:

['a foxy ','dog',' met a dogged ','fox']

I've tried various combinations but nothing is working for all parts, so any pointers would be much appreciated.我尝试了各种组合,但没有任何东西适用于所有部分,所以任何指针都将不胜感激。

Using a non-capturing group in combination with word boundaries would do it:结合单词边界使用非捕获组可以做到:

 const s = 'a foxy dog met a dogged fox'; const r = s.split(/(?:\b(dog|fox)\b)/); console.log(r);

If the empty segments bother you, you can easily filter them out:如果空段困扰您,您可以轻松地将它们过滤掉:

 const s = 'a foxy dog met a dogged fox'; const r = s.split(/(?:\b(dog|fox)\b)/).filter(x => x); console.log(r);

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

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