2

I have a CSS style that I need to extract the color from using a Java regex.

eg

color:#000;

I need to extract the thing after : to ;. Can anyone give an example?

0

4 Answers 4

2

I'm not sure how to apply it to Java, but one regex to do this would be:

^color:\s*(#[0-9a-f]+);?$

Sign up to request clarification or add additional context in comments.

2 Comments

On a sidenote: This variation will not match the more common version with one or more white spaces after the colon — e.g.: background-color: #fff;. Also note that the semi-colon might not be present after the last statement for a selector and should probably be optional. (There’s more issues like matching colors defined as rgb[a] values or named colors but they don’t necessarily fit in scope of this question.)
@polarblau, I have updated the regex to allow for optional spaces and semi-colon. I agree that your last point is outside the scope of this question.
1

To just extract from : up to ; do something like:

    Pattern pattern = Pattern.compile("[^:]*:(.*);");
    Matcher matcher = pattern.matcher(text);
    if (matcher.matches()) {
        String value = matcher.group(1);
        System.out.println("'" + value+ "'");  // do something with value
    }
  • [^:]* - any number of chars that are not ':'
  • : - one ':'
  • (...) - a capturing group
    • .*- any number of any character
  • ;- the terminating ';'

use color:(.*); for only accepting values for 'color'.

Comments

-1
/(?<=:).+(?=;)/

That will do it for you

Not sure how you implement regex in Java though.

www.regexr.com to help you text out your regex in real time.

Comments

-1

The expression

":(#.+);"

should do it

3 Comments

I wonder why people vote negative, the expression is correct and it is not missleading
Yes, but it is greedier than needed; better and safer to just match numbers; the regexp will be faster, and more accurate.
I agree that it could be better but then that is the purpose of this site, so that he can pick and accept another answer, your argument does not justify negative votes in my opinion, but again, this is just an opinion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.