[英]how to use regular expression to get value from string
我有以下字符串文本:
<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>
為了清楚起見,添加了換行符和標識,但實際字符串沒有它
如何獲得h2
顏色的值? 在這種情況下,應為- #e2703b;
在這種情況下,我不知道如何使用正則表達式。
如果我這樣嘗試更新 :
Match match = Regex.Match(cssSettings, @"h2 {color: (#[\d|[a-f]]{6};)");
if (match.Success)
{
string key = match.Groups[1].Value;
}
根本不起作用
我不確定正則表達式是否可行,但是您可以使用此正則表達式提取值:
h2 \\{color: (#(\\d|[a-f]){6};)}
從中獲得第一個組將獲得屬於h2顏色的值。
編輯
這段代碼應該得到它:
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;
正如您所說的,字符串中沒有制表符[\\ s]和換行符[\\ n] 。因此,正則表達式為:
(?<=[.]*h2{color:)[#\w]*(?=[.]*)
因此,代碼變成
Match match = Regex.Match(cssSettings, @"(?<=[.]*h2{color:)[#\w]*(?=[.]*)");
if (match.Success)
{
string key = match.Value;
}
嘗試這個:
@"h2\s*{\s*color: (#.{6};)"
這應該是相當可靠的。 可選空格,換行符和其他內容。 還查找半角顏色代碼,如果h2
沒有color
,則不跳到下一個塊。
h2\s*\{[^}]*color\s*:\s*?(#[a-f\d]{3}|#[a-f\d]{6})\b
結果在第一個也是唯一一個捕獲的組中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.