3 html regex perl html-parsing
我想从带有属性的 HTML 标签中提取标签名称。
例如,我有这个标签
<a href="http://chat.stackoverflow.com" class="js-gps-track" data-gps-track="site_switcher.click({ item_type:6 })"
>
Run Code Online (Sandbox Code Playgroud)
我需要提取标签名称 a
我尝试了以下正则表达式,但它不起作用。
if ( $raw =~ /^<(\S*).*>$/ ) {
print "$1 is tag name of string\n";
}
Run Code Online (Sandbox Code Playgroud)
我的代码有什么问题?
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+.*?>
Run Code Online (Sandbox Code Playgroud)
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
归档时间: |
|
查看次数: |
7797 次 |
最近记录: |