Extract an HTML tag name from a string

主宰稳场 提交于 2019-12-11 08:46:29

问题


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:


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




回答2:


let matchTagName = (markup) => {
  const pattern = /<([^\s>]+)(\s|>)+/
  return markup.match(pattern)[1]
}

matchTagName("<test>") // "test"
matchTagName("<test attribute>") // "test"
matchTagName("<test-dashed>") // "test-dashed"



回答3:


You can also try the following; it will match the tag name (always) + the attributes if they exist.

\<(?<name>\w+)(?<attributes>\s+[^>]*|)>



来源:https://stackoverflow.com/questions/28975162/extract-an-html-tag-name-from-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!