如何使用正则表达式来匹配css元素

时间:2012-05-29 04:47:23

标签: css regex

我正在indexOf的主题部分调用jQuery。我想看看CSS是否包含任何font-weight:bold属性。问题是,该财产可以有4种改变:

  1. font-weight:bold
  2. font-weight: bold
  3. font-weight :bold
  4. font-weight : bold
  5. 如何使用正则表达式匹配?

5 个答案:

答案 0 :(得分:4)

试试这个

\b(?:font-weight\s*:[^;\{\}]*?\bbold)\b

或者更好用:

\b(?:font-weight[\s*\\]*:[\s*\\]*?\bbold\b)

<强>解释

\b                # Assert position at a word boundary
(?:               # Match the regular expression below
   font-weight       # Match the characters “font-weight” literally
   [\s*\\]           # Match a single character present in the list below
                        # A whitespace character (spaces, tabs, and line breaks)
                        # The character “*”
                        # A \ character
      *                 # Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
   :                 # Match the character “:” literally
   [\s*\\]           # Match a single character present in the list below
                        # A whitespace character (spaces, tabs, and line breaks)
                        # The character “*”
                        # A \ character
      *?                # Between zero and unlimited times, as few times as possible, expanding as needed (lazy)
   \b                # Assert position at a word boundary
   bold              # Match the characters “bold” literally
   \b                # Assert position at a word boundary
)

希望这有帮助。

答案 1 :(得分:2)

请注意,font-weight:bold;也可以设置为an integer 700或通过简写font notation扩展字符串范围以匹配相当多。

\b(?:font.*?:[^;]*?\b(bold|700))\b

Fiddled

答案 2 :(得分:0)

试试这个:

/font-weight\: bold|font-weight\:bold|font-weight \:bold|font-weight \: bold/

答案 3 :(得分:0)

试试这个:

RegularExpressionValidator.ValidationExpression = "font-weight\s?:\s?bold"

答案 4 :(得分:0)

您无法使用正则表达式。 CSS可能包含类似的字符串

.foo{ content: "font-weight:bold;" }

您需要一个合适的解析器。幸运的是,浏览器有一个,并提供APIs来访问各个CSS规则。