Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract an HTML tag name from a string

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?


1 Answers

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

enter image description here

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

like image 101
Federico Piazza Avatar answered Oct 31 '25 04:10

Federico Piazza