首页 > 关于javascript正则的一个棘手问题

关于javascript正则的一个棘手问题

<section>
 
    //此处为任何内容,会动态改变
        
</section>
<table>
    //此处也为任何内容,会动态改变
</table>

以上内容以字符串形式复制给了变量str,我需要用正则从str中分别提取<section></section><table></table>之间的内容(包括section和table)赋值给str1和str2,我知道一般的正则方法,现在问题是两标签之间的内容可能会包含<section>或<table>,导致多匹配或少匹配。如/(<section>[\s\S]*<\/section>)|(<table[\s\S]*<\/div>)/
因为内容是随时变化的,请问有没有办法,在不受标签未知内容的影响下完美匹配?
有的话,请给个demo,谢谢!


根据楼上的答案在http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454里找到了一个大概能看懂的类似的问题,其中有一个点赞排名第二的人的回答:
While it is true that asking regexes to parse arbitrary HTML is like asking Paris Hilton to write an operating system, it's sometimes appropriate to parse a limited, known set of HTML.

If you have a small set of HTML pages that you want to scrape data from and then stuff into a database, regexes might work fine. For example, I recently wanted to get the names, parties, and districts of Australian federal Representatives, which I got off of the Parliament's Web site. This was a limited, one-time job.

Regexes worked just fine for me, and were very fast to set up.
edited Jul 23 '14 at 1:59

community wiki
3 revs, 3 users 73%
Kaitlin Duck Sherwood
根据词典翻译大概如下:然而这是事实,要求正则表达式分析任意HTML就像让帕丽斯·希尔顿写一个操作系统。去解析一个有限,已知的HTML是合适的。如果你有少量的HTML页面,要从中获取数据,然后到数据库的东西,正则表达式可能工作正常。例如,我最近想把名字、当事人以及澳大利亚联邦区代表,从Parliament's 网站上得到它们。这是一个有限的、一次性的工作。 正则表达式对我很好,是非常快速的建立。community wiki 3 revs, 3 users 73%
Kaitlin Duck Sherwoo
更新-:
如果只是套一对标签(比如section),匹配里面的任意内容好像是可以得,找到一个可以匹配嵌套标签的例子“平衡组的一个最常见的应用就是匹配HTML,下面这个例子可以匹配嵌套的<div>标签:<div[^>]*>[^<>]*(((?'Open'<div[^>]*>)[^<>]*)+((?'-Open'</div>)[^<>]*)+)*(?(Open)(?!))</div>...”http://c.biancheng.net/cpp/html/1419.html
不过这样还不是我想要的效果。


正则不清楚,既然是字符串,通过字符串的查找就能实现。
var pos = str.indexOf("<\/section><table>");

var getSection =str.subString(0,pos)+"<\/section>"

var getTable = "<table>"+str.subString(pos+("<\/section><table>".length))

这手机回答,太难受了,。。。。


http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454

【热门文章】
【热门文章】