简体   繁体   English

如何使用正则表达式选择此 HTML 代码?

[英]How to select this HTML codes using Regular Expression?

I have a few lines of HTML code :我有几行 HTML 代码:

 <div class="container header"> <div class="row"> <div class="col-md-6">This is the target text</div> </div> </div>

How to select everything inside the <div class="container header"> using Regular Expression ?如何使用正则表达式选择<div class="container header">

The end result should be :最终结果应该是:

 <div class="row"> <div class="col-md-6">This is the target text</div> </div>

How about this?这个怎么样?

<div class="row">[ \n\s]*<div class="col-md-6">[^<]*<\/div>[ \n\s]*<\/div>
  • [\\n\\s]* ensures you are only reading newspaces or spaces [\\n\\s]*确保您只阅读新空间或空间
  • [^<]* reads everything excluding < , which is the character you stop at [^<]*读取除<之外的所有内容,这是您停止的字符
  • <\\/div>[ \\n\\s]*<\\/div> reads the two closing div tags you requested <\\/div>[ \\n\\s]*<\\/div>读取您请求的两个结束 div 标签

Of course you must run it with the s option so that a dot matches newlines.当然,您必须使用s选项运行它,以便点与换行符匹配。

Live demo here现场演示在这里

DOMParser can be used to parse html: DOMParser可用于解析 html:

 var html = ` <div class="container header"> <div class="row"> <div class="col-md-6">This is the target text</div> </div> </div>` var innerHTML = new DOMParser().parseFromString(html, 'text/xml').firstChild.innerHTML console.log( innerHTML )

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

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