提问者:小点点

具有由多个字符组成的分隔符的正则表达式(除了普通的,1个字符的长分隔符)


我正在使用以下方法拆分。?!:;处的一些文本并保留分隔符:

var str = 'Hello! Here is a file. It is called beatles.mp3. And so on!';
let arr = str.match(/[^\/.?!:;]+(?:[\/.?!:;]|$)/g);
// output ==> ["Hello!", "Here is a file.", "It is called beatles.", "mp3.", "And so on!"]

这很好,但是我想有一种方法说(而且,就像我现在做的那样,保留分隔符):“在有.的地方拆分,但是如果有.,后面跟着MP3,我想你保留完整的.MP3。在其他地方,在有.的地方拆分。”

需要得输出:

["Hello!", "Here is a file.", "It is called beatles.mp3.", "And so on!"]

共2个答案

匿名用户

您可以尝试以下正则表达式:

const str = 'Hello! Here is a file. It is called beatles.mp3. And so on!';
const arr = str.match(/[^ ].+?(\.(?!mp3)|[\/?!:;])/g);

输出:

["Hello!", "Here is a file.", "It is called beatles.mp3.", "And so on!"]

匿名用户

您可以尝试:

((?:\.(?!mp3)|[!&^?:;/]))

上述正则表达式的说明:

  • (?:\。(?!mp3)-表示与不匹配的非捕获组。如果它前面有mp3
  • -表示交替。
  • [!&^?:;/]-表示可能发生拆分的标点符号。 您还可以添加其他标点符号。
  • $1\n-对于替换部分,使用捕获的组,后跟一个新行。 最后拆分结果字符串并删除后面出现的空格。

您可以在这里找到上述正则表达式的演示。

null

/*
const regex = /(?:\. (?!mp3)|[!&^?:;/] ?)/g;
const str = `Hello! Here is a file. It is called beatles.mp3. And so on!`;
console.log(str.split(regex).filter(el => el));
*/
const regex = /((?:\.(?!mp3)|[!&^?:;/]))/gm;
const str = `Hello! Here is a file. It is called beatles.mp3. And so on!`;
const subst = `$1\n`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

result.split("\n").forEach(el => console.log(el.trim()));