Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS regex to split by line

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"]

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.

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.

like image 864
JoJo Avatar asked Feb 17 '11 21:02

JoJo


People also ask

Can I use regex in Split Javascript?

You do not only have to use literal strings for splitting strings into an array with the split method. You can use regex as breakpoints that match more characters for splitting a string.

How do you split a string in regex?

To split a string by a regular expression, pass a regex as a parameter to the split() method, e.g. str. split(/[,. \s]/) . The split method takes a string or regular expression and splits the string based on the provided separator, into an array of substrings.

How do you split a string with multiple separators?

Use the String. split() method to split a string with multiple separators, e.g. str. split(/[-_]+/) . The split method can be passed a regular expression containing multiple characters to split the string with multiple separators.

How do you split a string into a new line in Python?

To split a string by newline character in Python, pass the newline character "\n" as a delimiter to the split() function. It returns a list of strings resulting from splitting the original string on the occurrences of a newline, "\n" .


1 Answers

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.

like image 191
ReactiveRaven Avatar answered Oct 04 '22 16:10

ReactiveRaven