我读了很多问题,但还没找到想要的问题.
我有一系列的话.
如何通过数组中的单词拆分字符串(使用正则表达式)?
例
var a=['john','paul',...];
var s = 'The beatles had two leaders , john played the guitar and paul played the bass';
Run Code Online (Sandbox Code Playgroud)
我想要的结果是一个数组:
['The beatles had two leaders , ' , ' played the guitar and ','played the bass']
Run Code Online (Sandbox Code Playgroud)
所以基本上约翰和保罗是分裂者.
我试过了什么:
我成功了:
var a='The beatles had two leaders , john played the guitar and paul played the bass'
var g= a.split(/(john|paul)/)
console.log(g)
Run Code Online (Sandbox Code Playgroud)
结果:
["The beatles had two leaders , ", "john", " played the guitar and ", "paul", " played the bass"]
Run Code Online (Sandbox Code Playgroud)
但我不希望保罗和约翰成为结果
题:
如何使用正则表达式通过单词数组拆分字符串?
注意,如果有很多john,请按第一个划分.
约翰和保罗在结果中的原因是你将它们包含在正则表达式的捕获组中.删除():
var g = a.split(/john|paul/);
Run Code Online (Sandbox Code Playgroud)
...或者如果你需要对交替进行分组(如果它本身就是这样),请在表单中使用非捕获组(?:john|paul):
var g = a.split(/blah blah (?:john|paul) blah blah/);
Run Code Online (Sandbox Code Playgroud)
您可以使用join和从数组中形成正则表达式new RegExp:
var rex = new RegExp(a.join("|"));
var g = a.split(rex);
Run Code Online (Sandbox Code Playgroud)
...但是如果可能存在正则表达式中特殊的字符,则需要map先将它们(可能正在使用)转义:
var rex = new RegExp(a.map(someEscapeFunction).join("|"));
var g = a.split(rex);
Run Code Online (Sandbox Code Playgroud)
这个问题的答案解决了创造问题someEscapeFunction,遗憾的是没有内置RegExp.