I googled this and looked on here and none of the answers seem to match the right thing for me. They seem to mostly return null
. I'm trying to search a CSS files with it with a CSS block like:
.twitterfeed p {
background: #fff;
border-radius: 15px;
color: #373737;
font-size: 15px;
margin: 0 10px 20px 10px;
-moz-border-radius: 开发者_如何学编程15px;
padding: 13px;
position: relative;
-webkit-border-radius: 15px
}
I didn't make the CSS file or anything so I don't know whats in it and I dont know if there will be new lines or single liners like: body { background:color; }
How can I match that entire block, but not other blocks? So, from something { }
?
var str = '.twitterfeed p {\
background: #fff;\
border-radius: 15px;\
color: #373737;\
font-size: 15px;\
margin: 0 10px 20px 10px;\
-moz-border-radius: 15px;\
padding: 13px;\
position: relative;\
-webkit-border-radius: 15px\
}';
var matches = str.match(/([^{]+\{[^}]+\})/g);
Here is a demo
You have to use something like
{[\S\s]*?}
Because Javascript does not know the dotall modifier s
to make the .
matches newlines you have to search for [\S\s]*
that means match a nonwhitespace character (\S
) or a whitespace character (\s
) zero or many times.
I made it a non greedy match *?
to avoid matching the last }
See it here online on Regexr
/\w+\s*{[^}]+}/
Finds simple CSS blocks when I try it on a multiline string. You'd have to add some characters to the capture group on the front of it to represent all of the possible tags and selector flags, though.
/[\w\*\.#>@ \t]+\s*{[^}]+}/
Might work for most tags but it's off the top of my head and I might be missing some flags.
More about the limitations of the JS regular expression language, if you're interested http://www.regular-expressions.info/javascript.html
If you just want what's between the curly brackets:
var m = myCssFileString.match(/\{[^\}]+\}/m);
The match will include the brackets - you can easily substring and trim to get just the defined styles.
精彩评论