JS RegEx to match all characters (including newlin

2019-05-10 05:01发布

问题:

Example Text:

<div id="not-wanted">
no no 
no 
</div>
<div id="wanted">I want 
only this 
text
</div> no no no
no no
<div id="not-wanted">
no no no 
</div>
<div id="wanted">no no
no no</div>
<div id="wanted">
no no     
</div>

Should deliver:

I want 
only this 
text

Or better:

I want only this text

Unfortunately, my solution catches the 2 delimitation strings also:

$('#put').append(/<div id="wanted">[^<>]*<\/div>/.exec(strg)[0]);

==>

<div id="wanted">I want 
only this 
text
</div>

Online example

http://regex101.com/r/rF7jR9

Question

What regular expression for Java Script can deliver the characters between delimiting strings, if there are also \n and \r resend. It would be nice, if \n and \r are removed from the delivered string. The RegExpr should work fast.

回答1:

Now I know how to:

$('#put').append(/<div id="wanted">([\s\S]*?)<\/div>/.exec(strg)[1]);

Thank you Jerry for the (group) hint. [\s\S] stands for every character. *? stop after first found <\/div>.



回答2:

You can use a capture group and ignore the full match?

$('#put').append(/<div id="wanted">([^<>]*)<\/div>/.exec(strg)[1]);
                                   ^------^                    ^

( ... ) is a capture group and since it's the first one in the regex, it gets to the first capture group, hence the 1 near the end.