开发者

How can I read classes, IDs or tags styles inside a text file using regular expression?

I have a problem with regular expression, I need a regular expression to read classes names with properties and the same thing with IDs and Tags styling, each match must have one block; class name (or classes names) with their style!

To explain my problem, the regular expression must match the following syntax of styling:

#myId {
    margin: 10px 8px 9px 0;
}

.myClass1 {
    margin: 10px -8px 9px 0;
    padding: 10px 8px 9px 0;
}

-my-tag {
    margin-down     :-10px;
    margin-left: 10px;
    margin-right: 10px;
}

-my-tag #my-id{
    margin-down     :-10px;
    margin-left: 10px;
    ma开发者_JAVA百科rgin-right: 10px;
}
#_myI4D6 {margin:10px;}

.myclass.myclass_too {
}
.myclass .myclass_too {                                
    margin-up:10px;
    bac: url "(../../image/p_n-G.png)";
    Margin: 10px 0 10PX 10Px;
    }

#myID .myclass:first-child my-tag {
     margin:     10px;
}

.emptyclass {
}
.classname 
tagnam {
  padding: 40px 999px        ; 
}

.className #myid
{
    maRgin: 10px 0 10px 10px;
}

the first match must be :

#myId {
        margin: 10px 8px 9px 0;
    }

On advanced if you can solve the comment problem, maybe class commented like:

/* #myId {
        margin: 10px 8px 9px 0;
    } */

I don't need to match it.

Note: I write a program using C#, and please note white spaces problems too (Tabs, newlines and spaces).


It seems like you're trying to implement CSS parsing in C#. I can't help you with the regex, but I would strongly suggest you avoid implementing such a thing yourself and use an existing CSS parsing library and save yourself tons of efforts.


try this with Regex.Matches

Regex.Matches(cssString, @"[^{]+\{[^}]+?}");

Each match should be a complete block.

From there you can get the selector from the bit up to the first '{' in each match.

Warning!

As Samir Talwar commented directly on your question - a regex approach is especially going to struggle with '{' and '}' characters nested within style rules; because Regex can't handle context.

You might want to look instead at a grammar-based solution with Antlr (steep learning curve but there is already a css 2.1 grammar if you search down this page); or indeed as other people have suggested, a parser specifically crafted towards parsing CSS.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜