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
JS regex to split by line
提问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.split
because I'll be dealing with both Linux \n
and Windows \r\n
line 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 line1
twice because line1
is both the entire match andthe contents of the first capturing group.
您的正则表达式返回line1
两次,因为line1
是整个匹配项和第一个捕获组的内容。
回答by Arup Hore
I am assuming following constitute newlines
我假设以下构成换行符
- \r followed by \n
- \n followed by \r
- \n present alone
- \r present alone
- \r 后跟 \n
- \n 后跟 \r
- \n 单独出现
- \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\n
with \n
, thenString.split
.
首先将所有替换\r\n
为\n
,然后替换为String.split
。
回答by Abhijit_Srikumar
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.
我做过这样的事情。上面的链接是我的小提琴。