user3791836 user3791836 - 1 year ago 54
Javascript Question

Get content with regex in javascript

line 1
line 2
line 3

content 1
content 2
content 3

How do I get "head" paragraph(first part) text with regex? This is from txt file.

Answer Source

this is a little fancy, but it should fit if this is used in conjunction with many similar properties.


Note that you need the /m multiline flag.

Here it is tested against your sample data

First, we check for the ::head data. That's where we start collecting information in a group with (). Then we look for anything with .*, but we do so with the lazy ? flag. Then we find the end of the line with $ and look for more lines with data with the line start ^ then anything .*? then the line end $ this will grab multiple lines because of the multiline flag, so it's important to use the lazy matching ? so we don't grab too much data. Then we look for an empty line. Normally you just need ^$ for that, but I wanted to make sure this would work if someone had stuck a stray space or tab on the lines in between sections, so we used \s* to grab spaces. The * allows it to find "0 or more" spaces as acceptable. Notice we didn't include the empty line in the group () because that's not the data you care about.

For further reading on regex, I recommend It's where I learned everything I know about regex.