Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use regular expression to get value from string

Tags:

c#

regex

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

like image 505
revolutionkpi Avatar asked May 29 '12 11:05

revolutionkpi


People also ask

How do you get a number from a string in regex?

Python Regex – Get List of all Numbers from String. To get the list of all numbers in a String, use the regular expression '[0-9]+' with re. findall() method. [0-9] represents a regular expression to match a single digit in the string.

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.

What is difference [] and () in regex?

[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9. (a-z0-9) -- Explicit capture of a-z0-9 .


1 Answers

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;
like image 124
Terry Avatar answered Oct 05 '22 22:10

Terry