no1uknow
no1uknow

Reputation: 549

Regular Expression to get "left" only from style

This is my regular expression to get "left" and its value.

/(left\s*:\s*)(\d+)?(px)/

My problem is, it pulls padding-left and left.

vertical-align: top; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; display: list-item; width: 420px; position: absolute; top: 0px; left: 700px; height: 580px;

How can I get "left" and its value only?

I put a \s in front of left and that works... But I can't always guarantee there will be a space in front of left.

Thanks...

Upvotes: 1

Views: 152

Answers (2)

rkyser
rkyser

Reputation: 3357

Instead of using a RegEx, you could use a CSS parser. This is a more robust solution as a parser is better suited for this task.

An example using Python and cssutils

example.css

.myClass {
    border: 1px solid black;
    margin-left: 100px;
    left: 700px;
    padding-left: 50px;
}

get-left.py

#!/usr/bin/env python

import cssutils
sheet = cssutils.parseFile('example.css')

for rule in sheet:
    if rule.type == rule.STYLE_RULE:
        for prop in rule.style:
            if prop.name == 'left':
                print("{0}: {1}".format(prop.name, prop.value))

In this Python script, prop.name will return the name of the property and prop.value its value.

output

$ ./get-left.py 
left: 700px

Upvotes: 0

MDEV
MDEV

Reputation: 10838

/(?:^|[^-])(left)\s*:\s*(\d+|auto)([a-z]{2})?/

Will fetch what you want with "left" in group 1, "700" in group 2 and "px" in group 3

(?:^|[^-]) = The start of the string, or a non-hyphen character

(left) = The word left (capture group 1)

\s*:\s* = A colon with optional space characters either side

(\d+|auto) = One or more numbers, or the string "auto" (capture group 2)

([a-z]{2})? = Two letters, e.g. "px" "em" "pt" (capture group 3 - optional)

Upvotes: 1

Related Questions