本文介绍了如何使用正则表达式来获得字符串值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我有这样的字符串文本: < META HTTP-EQUIV =Content-Type的内容=文/ HTML;字符集=utf-8> <风格类型=文/ CSS> 体{ FONT-FAMILY:宋体,Arial字体,无衬线; 字体大小:16像素; } H2 {颜色:#e2703b; } {.newsimage 保证金底:10px的; } {.date 文本对齐:右; FONT-SIZE:35px; } < /风格> 的新行和idents加为清楚起见,真正的字符串没有它的 我怎样才能获得 H2 颜色的价值?在这种情况下,它应该是 - #e2703b; 我不知道如何在这种情况下,使用正则表达式 更新 。如果我尝试这种方式: 匹配匹配= Regex.Match (cssSettings,@H2 {颜色:(#[\d | [AF] {6};)); 如果(match.Success) {串键= match.Groups [1] .value的; } 它不会在所有 工作解决方案 我不知道,如果正则表达式是要走的路,但你可以通过使用此正则表达式中提取值: H2 \\ {颜色:(#(\\d | [AF]){6})} 获取第一批来自这将让你属于H2的颜色值。 修改 这一段代码应该得到它: 字符串正则表达式=H2 \\ {颜色:(#(\\d | [AF]){6})}; 字符串输入=< META HTTP-当量= \内容Type\CONTENT = \text / html的; \字符集= \UTF-8\>< ;样式类型= \文/ css\>机身{FONT-FAMILY:宋体,Arial字体,无衬线; FONT-SIZE:16px的;} H {颜色:#e2703b;} {newsimage利润率底:10px的;}日期{文本对齐:右; FONT-SIZE:35px;}< /风格与GT; MatchCollection科尔= Regex.Matches(输入,正则表达式); 字符串结果=科尔[0] .Groups [1] .value的; 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 itHow 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.UpdateIf 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 解决方案 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.EditThis 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; 这篇关于如何使用正则表达式来获得字符串值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-24 22:39