JS RegEx to match all characters (including newline) between two strings but without the two strings?

久未见 提交于 2019-12-07 12:24:45

问题


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.



来源:https://stackoverflow.com/questions/22531252/js-regex-to-match-all-characters-including-newline-between-two-strings-but-wit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!