str = "This\n is a sample text for test"
str.scan(/\S.{0,15}\S(?=\s|$)|\S+/)
# => ["This", "is a sample text", "for test"]
Here, it splits when the newline (\n) is present. I actually want the output as,
["This\n is a", "sample text for", "test"]
How can I achieve that?
Use the
/mmodifier which allows the dot to match newlines:Also, I suggest you use
\zinstead of$because$matches the end of a line;\zis the only way to force Ruby to match the end of the string. It doesn’t matter in this example, but it’s a good habit to get into. Ruby differs from all other regex flavors in these two points.