首页 > 解决方案 > 用换行符匹配段落正则表达式

问题描述

我可以使用什么正则表达式来匹配段落(包括换行符),所以当我使用 时split(),我会得到一个数组,其中每个句子作为一个元素?

像这样的东西:

const paragraph = `
  one potatoe
  two apples
  three onions
`;

const arr = paragraph.split(/(.+?\n\n|.+?$)/);

我有那个返回的正则表达式,["one potatoe↵two apples↵", "three onions", ""]但我正在寻找的是["one potatoe", "two apples", "three onions"].

谢谢您的帮助!

编辑

每个句子由换行符分隔。所以在one potatoe有一个换行符(点击返回)然后来了two apples,换行符和three onions

标签: javascriptregex

解决方案


我了解您希望每一行都带有与后面一样多的相邻换行符的文本。

它会更容易使用match,而不是split

const paragraph = `
one potatoe
two apples

three onions`;

const arr = paragraph.match(/^.+$[\n\r]*/gm);

console.log(arr);


推荐阅读