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.
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.
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.
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.
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" .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With