Web & Software Developer

Regex Examples For Sublime Text 3 to Find an HTML Element with Included Content

These regular expression examples are useful in Sublime Text 3 when you enable “Find” by Regular Expression. You can search for an HTML element’s opening tag, closing tag, and included content in between. Also, you can specify attributes, or not. Please see the caveat below.

  1. This is a regex example to find an HTML element with attributes — find the opening tag, closing tag, and any content in between. This example searches for a “div” element, but you can replace the “div” at the beginning and end with the HTML element that you want to search for. Also, this example searches specifically for “div” elements that have the attribute “class” set to a value of “my-class”. You can replace that to specify the attribute that you need, for example, class=”some-other-class“. Note that it will find elements that have this attribute, but the elements may also have more attributes in addition to the specified attribute.

    <div[^<>]*class="my-class"[^<>]*>[\s\S]*?</div>
  2. The following example is just like above, except that it searches for “div” elements that have the “class” attribute set to anything. So, you don’t have to specify the value of the class attribute.

    <div[^<>]*class="[^"']+"[^<>]*>[\s\S]*?</div>
  3. This regex example is just like above, except that it works regardless of attributes. This will find an HTML element, its opening and closing tag, and any included content, regardless of attributes. So it will find the “div” elements that have any attributes, and also those that don’t have attributes. You can change the “div” at the beginning and end to the HTML element that you are searching for.

    <div[^<>]*[^<>]*>[\s\S]*?</div>

A Caveat

Beware that these examples will find the opening tag, and all included content, until it finds the first matching closing tag. So, in the case of 2 nested div elements, it will find the first opening div tag, and incorrectly match it to the first closing div tag. Beware of that.

By

We've 2 Responses

Questions and Comments are Welcome

Your email address will not be published. All comments will be moderated.

Please wrap code in "code" bracket tags like this:

[code]

YOUR CODE HERE 

[/code]