Search code examples
regexlua

Regex split string by new line and also include empty lines new lines


my_line = [[this
is
a

test]]

split_file = string.match(my_line, "[^\r\n]+|^[ \t\n]*$")
print(#split_file)

the above code doesn't work and I don't know why

string.match(my_line, "[^\r\n]+")

This works, but it only matches the words, so my array would look like this ["this", "is", "a", "test"]

While I want the array to be

["this", "is", "a", "\n", "test"]

Solution

  • Not sure which language are you using, so in JavaScript using global (g) and multi-line (m) flags -

    st = `this
    is
    a
    
    test`;
    console.log(JSON.stringify(st.match(/[^\r\n]+|^[ \t\n]*/gm))); // ["this","is","a","\n","test"]