从字符串中提取HTML标记名称 [英] Extract an HTML tag name from a string

查看:101
本文介绍了从字符串中提取HTML标记名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从具有属性的HTML标记中提取标记名称.

I want to extract the tag name from an HTML tag with attributes.

例如,我有这个标签

 <a href="http://chat.stackoverflow.com" class="js-gps-track"     data-gps-track="site_switcher.click({ item_type:6 })"
>

,我需要提取标签名称a

and I need to extract the tag name a

我已经尝试了以下正则表达式,但是它不起作用.

I have tried the following regex, but it doesn't work.

if ( $raw =~ /^<(\S*).*>$/ ) {
   print "$1 is tag name of string\n";
}

我的代码有什么问题?

推荐答案

您的正则表达式与新行不匹配.您必须使用s标志(单行),但是由于您的正则表达式过于贪婪,因此它也不起作用,我也将删除锚点,因为它可能在同一行中是多个标签.

Your regex is not matching the new line. You have to use s flag (single line) but since your regex is greedy it won't work either, also I'd remove anchors since it might be several tags in the same line.

您可以使用这样的正则表达式:

You can use a regex like this:

<(\w+)\s+\w+.*?>

工作演示

Working demo

支持Borodin的评论,您不应该使用正则表达式来解析html,因为您可能会遇到解析问题.您可以使用正则表达式来解析像您一样的简单标签,但是如果您的文本带有诸如<a asdf<as<asdf>df>>之类的嵌入标签,则可以很容易地将其破坏,在这种情况下,正则表达式将只匹配标签a

Supporting Borodin's comment, you shouldn't use regex to parse html since you can face parse issues. You can use regex to parse simple tags like you have but this can be easily broken if you have text with embedded tags like <a asdf<as<asdf>df>>, in this case the regex will wronly match the tag a

此正则表达式背后的想法是强制标签至少具有一个属性

The idea behind this regex is to force tags to have at least one attribute

这篇关于从字符串中提取HTML标记名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆