Javascript JS正则表达式按行拆分

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5034781/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:21:54  来源:igfitidea点击:

JS regex to split by line

javascriptregexnewline

提问by JoJo

How do you split a long piece of text into separate lines? Why does this return line1twice?

你如何将一段很长的文本分成单独的行?为什么这个返回line1两次?

/^(.*?)$/mg.exec('line1\r\nline2\r\n');

["line1", "line1"]

["line1", "line1"]

I turned on the multi-line modifier to make ^and $match beginning and end of lines. I also turned on the global modifier to capture alllines.

我打开了多行修饰符来制作^$匹配行的开头和结尾。我还打开了全局修饰符以捕获所有行。

I wish to use a regex split and not String.splitbecause I'll be dealing with both Linux \nand Windows \r\nline endings.

我希望使用正则表达式拆分,而不是String.split因为我将同时处理 Linux\n和 Windows\r\n行尾。

回答by ReactiveRaven

arrayOfLines = lineString.match(/[^\r\n]+/g);

As Tim said, it is both the entire match and capture. It appears regex.exec(string)returns on finding the first match regardless of global modifier, wheras string.match(regex)is honouring global.

正如蒂姆所说,这既是整场比赛,也是捕获。regex.exec(string)无论全局修饰符如何,它似乎都会在找到第一个匹配项时返回,而string.match(regex)尊重全局。

回答by Tim Pietzcker

Use

result = subject.split(/\r?\n/);

Your regex returns line1twice because line1is both the entire match andthe contents of the first capturing group.

您的正则表达式返回line1两次,因为line1是整个匹配项第一个捕获组的内容。

回答by Arup Hore

I am assuming following constitute newlines

我假设以下构成换行符

  1. \r followed by \n
  2. \n followed by \r
  3. \n present alone
  4. \r present alone
  1. \r 后跟 \n
  2. \n 后跟 \r
  3. \n 单独出现
  4. \r 单独出现

Please Use

请用

var re=/\r\n|\n\r|\n|\r/g;

arrayofLines=lineString.replace(re,"\n").split("\n");

for an array of all Lines including the empty ones.

对于包括空行在内的所有行的数组。

OR

或者

Please Use

请用

arrayOfLines = lineString.match(/[^\r\n]+/g); 

For an array of non empty Lines

对于非空行的数组

回答by ciscoheat

Even simpler regex that handles all line ending combinations, even mixed in the same file, and removes empty lines as well:

更简单的正则表达式处理所有行结束组合,甚至混合在同一个文件中,并删除空行:

var lines = text.split(/[\r\n]+/g);

var lines = text.split(/[\r\n]+/g);

With whitespace trimming:

使用空白修剪:

var lines = text.trim().split(/\s*[\r\n]+\s*/g);

var lines = text.trim().split(/\s*[\r\n]+\s*/g);

回答by Tim

First replace all \r\nwith \n, thenString.split.

首先将所有替换\r\n\n然后替换为String.split

回答by Abhijit_Srikumar

http://jsfiddle.net/uq55en5o/

http://jsfiddle.net/uq55en5o/

var lines = text.match(/^.*((\r\n|\n|\r)|$)/gm);

var lines = text.match(/^.*((\r\n|\n|\r)|$)/gm);

I have done something like this. Above link is my fiddle.

我做过这样的事情。上面的链接是我的小提琴。