Regex to match a CSS class name

后端 未结 2 461
无人及你
无人及你 2021-01-02 04:48

I am trying to write a regex that matches a valid CSS class name structure. I have this so far:

$pattern = \"([A-Za-z]*\\.[A-Za-z]+\\s*{)\";

$regex = preg_m         


        
相关标签:
2条回答
  • 2021-01-02 05:36

    Have a look at http://www.w3.org/TR/CSS21/grammar.html#scanner

    According to this grammar and the post Which characters are valid in CSS class names/selectors? this should be the right pattern to scan for css classes:

    \.-?[_a-zA-Z]+[_a-zA-Z0-9-]*\s*\{
    

    Note: Tag names are not required as prefix for classes in css. Just .hello { border: 1; } is also valid.

    0 讨论(0)
  • 2021-01-02 05:37

    This regex:

    /(\w+)?(\s*>\s*)?(#\w+)?\s*(\.\w+)?\s*{/gm
    

    will match any of the following:

    p.my_class{}
    p.thisclas45{}
    .simple_class{}
    tag#id.class{}
    tag > #id{}
    

    You can play around with it, on RegExr, here.

    0 讨论(0)
提交回复
热议问题