如何在CSS中编写正则表达式

时间:2011-07-09 21:18:23

标签: css regex css-selectors

如何在CSS中使用正则表达式?我找到了一个教程here来匹配CSS中的静态字符串,但我找不到使用正则表达式来匹配CSS中的多个字符串。 (我发现了一个here,但我无法让它工作。我也看了W3C documentation on using regular expressions,但我无法理解文档。)

我想匹配一系列<DIV>代码,这些代码的ID从s1开始并增加1(即#s1 #s2 #s3 ...)。

我知道div[id^=s]div[id^='s']div[id^='s']各自执行匹配,因为我打算在CSS中使用它。但是,每个都匹配#section的id,我不想发生。我相信"/^s([0-9])+$/"是等效的PHP字符串 - 我只是在CSS版本中寻找它。

5 个答案:

答案 0 :(得分:3)

无法将元素与正则表达式even in CSS3匹配。您最好的选择可能只是使用div的课程。

<style>
.s-div {
    // stuff specific to each div
}
</style>

<div id="s1" class="s-div"><!-- stuff --></div>
<div id="s2" class="s-div"><!-- stuff --></div>
<div id="s3" class="s-div"><!-- stuff --></div>
<div id="s4" class="s-div"><!-- stuff --></div>
<div id="s5" class="s-div"><!-- stuff --></div>

另请注意,您可以使用class属性中的空格分隔多个类名。

<div class="class1 class2 class3"></div>

答案 1 :(得分:1)

javascript:
    /* page scrape the DIV s# id's and generate the style selector */
    re=/<div\b[^>]*\b(id=(('|")?)s[0-9]+\2)(\b[^>]*)?>/ig;
    alert(
        document . body . innerHTML .
            match(re) . join("") .
                replace(re,"div[$1], ") + "{ styling details here }" );

    alert(
       ("test with <div id=s2 aadf><DIV ID=123> <DIV adf=asf as><Div id='s45'>" +
              "<div id=s2a ><DIV ID=s23 > <DIV asdf=as id=S9 ><Div id='x45' >") .
            match(re) . join("") .
                replace(re,"div[$1], ") + "{ styling details here }"
        );

测试结果

div[id=s2], div[id='s45'], div[ID=s23], div[id=S9], { styling details here }

请注意悬空,和案例保留S9

答案 2 :(得分:0)

如果您不想或不能使用@zneak发布的解决方案,您可以使用javascript编辑标签,但我会建议您:这是一个很糟糕的工作。

答案 3 :(得分:0)

以下CSS会选择#s0, #s1, ... , #s9而不是#section,但浏览器必须实施CCS3否定:not()。 最终选择相当于:

/^s[0-9]?.*[0-9]$/

表示每个ID必须以s和一个数字开头,并以数字结尾:

s6, s42, s123, s5xgh7, ...

:not()行真空排除那些使用空样式{}无法正常启动的ID。

<style>
div:not([id^=s0]):not([id^=s1]):not([id^=s2]):not ... :not([id^=s9]) {}
div[id^=s][id$=0], div[id^=s][id$=1], div[id^=s][id$=2], ... div[id^=s][id$=9] { ... }
</style>

CSS3不使用正则表达式来定义选择器但是...
CSS Conditional Rules Module Level 3
定义了一个非常具体的函数regexp(< string >),它在创建 @document时用正则表达式解析URL 规则。

答案 4 :(得分:0)

<style>
/* eliminate the alphabet except s - NB some funny characters may be left */
/* HTML id's are case-sensitive - upper case may need exclusion & inclusion */
div[id*=a], div[id*=b], div[id*=c], ..., div[id*=q], div[id*=r] {}
div[id*=t], div[id*=u], div[id*=v], div[id*=w], div[id*=x], div[id*=y], div[id*=z] {}
div[id*='_'], div[id*='-'], div[id*='%'], div[id*='#'] {}

/* s can not be embedded */
div[id*=0s], div[id*=1s], div[id*=2s], ..., div[id*=9s] {}

/* s will be followed by a string of numerals - maybe a funny char or two */
div[id^=s0], div[id^=s1], div[id^=s2], ... div[id^=s9] { ... }
</style>
相关问题