Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript regex to match multiple lines [duplicate]

my multiple string is something like below

###
some content
that I need to match
and might have some special character in it such as | <> []
###

I am trying to get the content of between hashes. I have tried below regex but it is not matching to it and return null.

var regex = /### ((.|\n)*) ###/;
var match= regex.exec(aboveContentAsString);
console.log(match[1]);
like image 227
rawData Avatar asked Mar 05 '15 23:03

rawData


1 Answers

JavaScript lacks the s (singleline/dotall) regex option, but you can workaround it by replacing . with [\s\S] (match any character that is a whitespace or that is not a whitespace, which basically means match everything). Also, make your quantifier lazy and get rid of the spaces in the pattern, since there's also no x (extended) option in JS:

var regex = /###([\s\S]*?)###/;

Example:

var input = "###\nsome content\nthat I need to match\nand might have some special character in it such as | <> []\n###";

var regex = /###([\s\S]*?)###/;
document.getElementById("output").innerText = regex.exec(input)[1];
<pre id="output"></pre>

Your original approach could have worked, but I'd add \r in there too:

var regex = /###((?:.|[\r\n])*?)###/;

But I prefer the [\s\S] approach since it's shorter and (IMHO) more readable.

like image 85
Lucas Trzesniewski Avatar answered Oct 14 '22 04:10

Lucas Trzesniewski