I wrote a regex to fetch string from html, but it seems the multiline flag doesn't work.
this is my pattern and I want to get the text in h1 tag.
var pattern= /<div class="box-content-5">.*<h1>([^<]+?)<\/h1>/mi
m = html.search(pattern);
return m[1];
I created a string to test it. When the string contains "\n" the result is always null. If I remove all the "\n" , it gave me the right result, no matter with or without /m flag.
what's wrong with my regex?
[\s\S]
did not work for me in nodejs 6.11.3. Based on the RegExp documentation, it says to use[^]
which does work for me.For example:
/This is on line 1[^]*?This is on line 3/m
where the *? is the non-greedy grab of 0 or more occurrences of [^].
The dotall modifier has actually made it into JavaScript in June 2018, that is ECMAScript 2018.
https://github.com/tc39/proposal-regexp-dotall-flag
You want the
s
(dotall) modifier, which apparently doesn't exist in Javascript - you can replace.
with [\s\S] as suggested by @molf. Them
(multiline) modifier makes ^ and $ match lines rather than the whole string.You are looking for the
/.../s
modifier, also known as the dotall modifier. It forces the dot.
to also match newlines, which it does not do by default.The bad news is that it
does not exist in JavaScript(it does as of ES2018, see below). The good news is that you can work around it by using a character class (e.g.\s
) and its negation (\S
) together, like this:So in your case the regex would become:
As of ES2018, JavaScript supports the
s
(dotAll) flag, so in a modern environment your regular expression could be as you wrote it, but with ans
flag at the end (rather thanm
;m
changes how^
and$
work, not.
):