 module.exports =
 class TagFinder
   constructor: (@editor) ->
-    @tagPattern = /(<(\/?))([^\s>]+)([\s>]|$)/
-    @wordRegex = /[^>\r\n]*/
+    @tagPattern = /(<(\/?))([^\/\s>]+)((?:[^\/>]|[^>](?!>))*)(\/?)(>)/
+    @wordRegex = /(?!$)[^>]*>/
     @tagSelector = SelectorCache.get('meta.tag | punctuation.definition.tag')
     @commentSelector = SelectorCache.get('comment.*')
 
   patternForTagName: (tagName) ->
     tagName = _.escapeRegExp(tagName)
-    new RegExp("(<#{tagName}([\\s>]|$))|(</#{tagName}>)", 'gi')
+    new RegExp("(<#{tagName}((?:[^\/>]|[^>](?!>))*)(>))|(<\/#{tagName}>)", 'gi')
 
   isRangeCommented: (range) ->
     scopes = @editor.scopeDescriptorForBufferPosition(range.start).getScopesArray()

  findEnclosingTags: ->
    if ranges = @findStartEndTags()
      if @isTagRange(ranges.startRange) and @isTagRange(ranges.endRange)
        return ranges

    null

    @editor.backwardsScanInBufferRange @tagPattern, [[0, 0], endPosition], ({match, range, stop}) =>
      stop()

      [entireMatch, prefix, isClosingTag, tagName, attributes, isSelfClosingTag, suffix] = match

      if range.start.row is range.end.row
        startRange = range.translate([0, prefix.length], [0, -(attributes.length + isSelfClosingTag.length + suffix.length)])
      else
        startRange = Range.fromObject([range.start.translate([0, prefix.length]), [range.start.row, tagName.length+1]])

      if isClosingTag
        endRange = @findStartTag(tagName, startRange.start)
      else
        endRange = @findEndTag(tagName, startRange.end)

      if isSelfClosingTag
        endRange = startRange

      ranges = {startRange, endRange} if startRange? and endRange?
    ranges
