简体   繁体   English

JS RegEx匹配两个字符串之间但没有两个字符串的所有字符(包括换行符)?

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

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: 不幸的是,我的解决方案还捕获了2个定界字符串:

$('#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 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. 如果还有\\n\\r重新发送,Java Script的正则表达式可以在分隔字符串之间传递字符。 It would be nice, if \\n and \\r are removed from the delivered string. 如果从传递的字符串中删除\\n\\r ,那就太好了。 The RegExpr should work fast. RegExpr应该可以快速工作。

Now I know how to: 现在我知道如何:

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

Thank you Jerry for the ( group ) hint. 谢谢Jerry的(小组)提示。 [\\s\\S] stands for every character. [\\s\\S]代表每个角色。 *? stop after first found <\\/div> . 在第一次找到<\\/div>后停止。

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. ( ... )是一个捕获组,因为它是正则表达式中的第一个,它到达第一个捕获组,因此接近结束时的1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM