eddyuk
eddyuk

Reputation: 4190

How to use regex to match css elements

I'm calling indexOf on the head section in jQuery. I want to see if CSS contains any font-weight:bold property. The issue is, that property can have 4 alters:

  1. font-weight:bold
  2. font-weight: bold
  3. font-weight :bold
  4. font-weight : bold

How can I match this using regex?

Upvotes: 3

Views: 730

Answers (5)

user123444555621
user123444555621

Reputation: 153204

You cannot use regular expressions for that. CSS may contain strings like so

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

You need a proper parser. Luckily the browser has one and offers APIs to access the individual CSS rules.

Upvotes: 0

Cylian
Cylian

Reputation: 11181

Try this

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

or would be better to use:

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

Explanation

\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
)

Hope this helps.

Upvotes: 4

Oleg
Oleg

Reputation: 25008

Remember that font-weight:bold; could also be set as an integer 700 or through a shorthand font notation which expands the range of strings to match quite a bit.

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

Fiddled

Upvotes: 2

Vinod
Vinod

Reputation: 4892

Try this:

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

Upvotes: 0

Someth Victory
Someth Victory

Reputation: 4559

Try this:

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

Upvotes: 0

Related Questions