panthro
panthro

Reputation: 24061

Check for HTML tags

I'm trying to write a regular expression to find out if there are any HTML tags, so far I have:

/^[^<>]+$/

It's for a validator, if no HTML tags exist, it will validate.

Upvotes: 0

Views: 177

Answers (2)

Federico Piazza
Federico Piazza

Reputation: 30985

You use a regex like this:

.*<\/?.*?>.*

Working demo

The idea is to find strings with tags like <tag>, <tag withAttribute="something"> or </closingTag>

enter image description here

Update: as Mr. Llama pointed in his comment you could enable s flag to enable . to match all. This will help you with multiple line strings.

(?s).*<\/?.*?>.*
 ^--- use this for inline single line flag or use the first regex but enable the `s` flag

Working demo

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626689

You can use the adapted version of the regex in this SO post:

^((?!<[^<]+>)[\s\S])*$

See demo.

Perhaps, you can further enhance it to only match if the first character after < is a letter:

^((?!<[a-zA-Z][^<]*>)[\s\S])*$

See another demo

Upvotes: 2

Related Questions