关于获取标签对内容的正则...实在写不出来, 伸手了...

2014-08-11 11:13:37 +08:00
 supman
<span class="large_name">The information</span>

标签对中的The information就是想要通过正则获取的内容, 试了N多..找了N多 还是不能只匹配想要的信息, 只好做回伸手党了, 请大家帮帮忙啦:) ^_^
2241 次点击
所在节点    问与答
8 条回复
n
2014-08-11 11:22:57 +08:00
'<span class="large_name">The information</span>'.match('<span class="large_name">(.*)</span>')[1];

这样行么?
RoshanWu
2014-08-11 11:28:46 +08:00
```js
var ss = '<span class="large_name">The information</span>'; ss.replace(/(<span[^>]*?>)(.*?)(<\/span>)/g, '$1replace content here$3');
```
mornlight
2014-08-11 12:03:26 +08:00
(?<=<span class="large_name">)[\s\S]+?(?=</span>)

这个是最简单粗暴的
imn1
2014-08-11 12:29:25 +08:00
<(\S+)\s?[^>]*?>[\s\S]+?</\s?\1>
iyaozhen
2014-08-11 13:13:19 +08:00
php:

preg_match("/<span class=\"large_name\">(.+?)<\/span>/",
'<span class="large_name">The information</span>', $matches);

print_r($matches);

Array
(
[0] => <span class="large_name">The information</span>
[1] => The information
)
aa65535
2014-08-11 14:01:30 +08:00
给个 js 的吧,其他也基本通用
'<span class="large_name">The information</span>'.match(/<(span)[^>]*>(.*?)<\/\1>/);
如果想匹配其他标签可以直接加,像这样 /<(span|div|pre)[^>]*>(.*?)<\/\1>/
abscon
2014-08-14 09:00:37 +08:00
@supman 楼主的需求还不够明确,是任意合法的html/xml里取得类名为large_name的标签对的内容么?标签名一定是span?这个内容可否包含其他的标签对?如果支持CDATA的话,那这个内容可否包含CDATA?这个标签对 <span class="large_name" />的内容是否算空?

建议楼主“放下正则,回头是岸”,找一个html/xml parser吧,正则不是什么都能干的。

你看栈溢网上的洋大人都发怒了: http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags

@n
@RoshanWu
@mornlight
@imn1
@iyaozhen
@aa65535
iyaozhen
2014-08-14 09:12:47 +08:00
@abscon 推荐一个php的html parser https://github.com/bupt1987/html-parser

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/127180

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX