简体   繁体   English

使用正则表达式将字符串拆分为不包括单词的数组

[英]Split string into an array with regular expression excluding a word

There was a question asked today, that piqued my interest (and subsequently was deleted) where the user wanted to split the following string with a regular expression今天问了一个问题,这引起了我的兴趣(随后被删除),用户想用正则表达式拆分以下字符串

'The 1. cat 2. sat 3. on 4. the 5. mat';

into this array进入这个数组

["cat","sat","on","the","mat"]

there were answers with this expression有这个表达的答案

str.match(/[a-z]+/gi);

which of course returns这当然会返回

["The","cat","sat","on","the","mat"]

The nearest I come come to an answer was with我最接近的答案是

str.match(/[^The][a-z]+/gi);

which returns返回

[" cat"," sat"," on"," the"," mat"]

Unit tested here单元测试在这里

Of course this can be done, but how?这当然可以做到,但是怎么做呢?

How about怎么样

Javascript Javascript

var str = 'The 1. cat 2. sat 3. on 4. the 5. mat',
    arr1 = str.match(/[a-z]+/gi),
    arr2 = str.match(/\b[a-z]+/g);

console.log(arr1);
console.log(arr2);

Output输出

["The", "cat", "sat", "on", "the", "mat"] 
["cat", "sat", "on", "the", "mat"] 

On jsFiddlejsFiddle 上

str.match(/\b(?!The\b)[a-z]+\b/gi)

您可以使用此模式:

str.match(/\b[a-z]+\b(?!\s1\.)/gi)

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

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