Regular expression to match style = "whatever: 0; morestuff: 1; otherstuff: 3"

I am trying to match something between and style=""
for example: style="whatever:0; morestuff:1; otherstuff:3"

+6
regex
source share
4 answers

The template will be /style="([^"]*)"/ , but may vary slightly depending on which language you use.

Also, if you try to do it through javascript, jquery will do it as simple as

 $("#element-id").attr("style"); 

If you are trying to do this from a different language, use the HTML parsing library as HTML is not regular. BeautifulSoup for Python is not bad.

+11
source share

String in test

 style="whatever:0; morestuff:1; otherstuff:3" 

Regex

 style\s*=\s*"([^"]*)" 

Group Content 1

 whatever:0; morestuff:1; otherstuff:3 


Note!

It is very difficult to write a regular expression parser that is correct, safe, and supported. If you need to write a program that deals with HTML in a reliable, reliable and safe way, you should use a real HTML parsing library such as jsoup (Java) or the Html Agility Pack (C #). To find the HTML parser for your favorite language, Google: yourlanguage html parser .

+3
source share

If you need to remove all style tags from html (completely clear inline styles), use this as regexp:

 style=\"[^\"]*\" 

This works for me in sublime text 2-3

+3
source share
 /(style="([^"]*)")/ 

for the entire line (unchecked). Do you also want to get key value pairs?

+1
source share

All Articles