revolutionkpi
revolutionkpi

Reputation: 2682

how to use regular expression to get value from string

I have this string text:

    <meta http-equiv="Content-Type" content="text/html;" charset="utf-8">
    <style type="text/css">
        body {
            font-family: Helvetica, arial, sans-serif;
            font-size: 16px;
        }
        h2 {
            color: #e2703b;
        }.newsimage{
            margin-bottom:10px;
        }.date{
            text-align:right;font-size:35px;
        }
    </style>

Newlines and idents are added for clarity, real string does not have it

How can I get value of h2 color? In this case it should be - #e2703b; I don't know how to use regular expressions in this case.

Update If I try this way:

Match match = Regex.Match(cssSettings, @"h2 {color: (#[\d|[a-f]]{6};)");
                    if (match.Success)
                    {
                        string key = match.Groups[1].Value;
                    }

it doesn't work at all

Upvotes: 6

Views: 50571

Answers (4)

primfaktor
primfaktor

Reputation: 2997

This should be quite robust wrt. optional spaces, line breaks and stuff. Also finds half-width color codes and does not jump into the next block if h2 has no color.

h2\s*\{[^}]*color\s*:\s*?(#[a-f\d]{3}|#[a-f\d]{6})\b

Result in the first and only captured group.

Try it!

Upvotes: 0

CB.
CB.

Reputation: 60910

Try this:

@"h2\s*{\s*color: (#.{6};)"

Upvotes: 0

Terry
Terry

Reputation: 5262

I'm not sure if regex is the way to go, but you can extract the value by using this regex:

h2 \\{color: (#(\\d|[a-f]){6};)}

Getting the first Group from this will get you the value that belongs to the color of the h2.

Edit

This piece of code should get it:

String regex = "h2 \\{color: (#(\\d|[a-f]){6};)}";
String input = "<meta http-equiv=\"Content-Type\" content=\"text/html;\" charset=\"utf-8\"><style type=\"text/css\">body {font-family: Helvetica, arial, sans-serif;font-size: 16px;}h2 {color: #e2703b;}.newsimage{margin-bottom:10px;}.date{text-align:right;font-size:35px;}</style>";
MatchCollection coll = Regex.Matches(input, regex);
String result = coll[0].Groups[1].Value;

Upvotes: 9

gout
gout

Reputation: 812

As you have said there are no tabs[\s] and line feeds[\n] in the string.Hence the regular expression would be:

(?<=[.]*h2{color:)[#\w]*(?=[.]*)

Hence the code becomes,

Match match = Regex.Match(cssSettings, @"(?<=[.]*h2{color:)[#\w]*(?=[.]*)");
                if (match.Success)
                {
                    string key = match.Value;
                }

Upvotes: 2

Related Questions