I want to extract the tag name from an HTML tag with attributes.
For example, I have this tag
<a href="http://chat.stackoverflow.com" class="js-gps-track" data-gps-track="site_switcher.click({ item_type:6 })"
>
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";
}
What is wrong with my code?
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

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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With