[英]Split string into an array with regular expression excluding a word
今天问了一个问题,这引起了我的兴趣(随后被删除),用户想用正则表达式拆分以下字符串
'The 1. cat 2. sat 3. on 4. the 5. mat';
进入这个数组
["cat","sat","on","the","mat"]
有这个表达的答案
str.match(/[a-z]+/gi);
这当然会返回
["The","cat","sat","on","the","mat"]
我最接近的答案是
str.match(/[^The][a-z]+/gi);
返回
[" cat"," sat"," on"," the"," mat"]
单元测试在这里
这当然可以做到,但是怎么做呢?
怎么样
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);
输出
["The", "cat", "sat", "on", "the", "mat"]
["cat", "sat", "on", "the", "mat"]
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.