V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
supman
V2EX  ›  问与答

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

  •  
  •   supman · 2014-08-11 11:13:37 +08:00 · 2231 次点击
    这是一个创建于 3567 天前的主题,其中的信息可能已经有所发展或是发生改变。
    <span class="large_name">The information</span>

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

    这样行么?
    RoshanWu
        2
    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
        3
    mornlight  
       2014-08-11 12:03:26 +08:00
    (?<=<span class="large_name">)[\s\S]+?(?=</span>)

    这个是最简单粗暴的
    imn1
        4
    imn1  
       2014-08-11 12:29:25 +08:00
    <(\S+)\s?[^>]*?>[\s\S]+?</\s?\1>
    iyaozhen
        5
    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
        6
    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
        7
    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
        8
    iyaozhen  
       2014-08-14 09:12:47 +08:00
    @abscon 推荐一个php的html parser https://github.com/bupt1987/html-parser
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   3000 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 41ms · UTC 11:07 · PVG 19:07 · LAX 04:07 · JFK 07:07
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.