JS正则表达式逐行分割 [英] JS regex to split by line

查看:500
本文介绍了JS正则表达式逐行分割的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将一段长文本分成不同的行?为什么这会两次返回 line1

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

/^(.*?)$/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 all lines.

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

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.

推荐答案

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

正如蒂姆所说,这是整个比赛和捕获。看起来 regex.exec(字符串)返回查找第一个匹配而不管全局修饰符,wheras string.match(regex)表彰全球。

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.

这篇关于JS正则表达式逐行分割的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆