How to extract CSS color using regex?
I have a CSS style that I need to extract the color from using a Java regex.
eg
color:#000;
I nee开发者_JS百科d to extract the thing after :
to ;
. Can anyone give an example?
I'm not sure how to apply it to Java, but one regex to do this would be:
^color:\s*(#[0-9a-f]+);?$
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'.
/(?<=:).+(?=;)/
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.
The expression
":(#.+);"
should do it
精彩评论