2017-09-16 37 views
-1

我的c#应用程序的目标是从文本文档中提取2个十进制值(纬度,经度)。我尝试应用模板来获取这些数字。它是一个Framework-3.5平台的旧版应用程序。c#正则表达式(RegEX)匹配组未能返回匹配的字符

using System.Text.RegularExpressions; 

String BB = "<span style=\"font-family:&quot;Times&quot;,&quot;serif&quot;\">\r\n<i>Lat</i>: 29.48434, <i>Long</i>: -81.562445 <o:p></o:p></span></p>\r\n</td>\r\n</tr>\r\n</tbody>\r\n</table>\r\n<p class=\"MsoNormal\"><span style=\"font-family:&quot;Times&quot;,&quot;serif&quot;\"><o:p>&nbsp;</o:p></span></p>\r\n<table class=\"MsoNormalTable\" border=\"0\" cellpadding=\"0\">\r\n<tbody>\r\n<tr>\r\n<td style=\"padding:.75pt .75pt .75pt .75pt\">\r\n<p class=\"MsoNormal\"><b><span style=\"font-family:&quot;Times&quot;,&quot;serif&quot;\">Coordinates:</span></b><span style=\"font-family:&quot;Times&quot;,&quot;serif&quot;\">\r\n<i>Lat</i>: 29.48434, <i>Long</i>: -81.562445 <o:p></o:p></span></p>\r\n</td>"; 

string p2 = @".*Lat\D+(-*[0-9]+\.[0-9]+)\D+Lon\D+(-*[0-9]+\.[0-9]+)"; 

Console.WriteLine(p2); 
foreach (Match collection in Regex.Matches(BB, p2)) { 
    foreach (Group gp in collection.Groups) { 
     Console.WriteLine("Match group {0}", gp.Value); 
    } 
} 

我预计集团的输出[2]应该有“ - ” 81.562445前的迹象,但它看起来像它甚至已经放弃了它它匹配模板“( - * [0-9] + [ 0-9] +)“!!!我能做些什么来让团队用' - '符号显示吗?

picture of output

+0

您没有文字。你有一个HTML文件,应该使用HTML技术,而不是正则表达式。正则表达式是正则表达式,HTML不规则。 – jdweng

+0

想到这个。只是我不应该认为HTML标签和lat-long之间没有任何内容,这意味着我仍然必须应用“常规”模板。可能只是首先要做到这一点! “\ D +?\ d”是涵盖任何可能性的最佳选择! –

回答

2

你的模式是寻找经度和纬度值之前,非数字字符(\D+)和-所以它被捕获不是一个数字。为了使非数字匹配非贪婪,使用一个?序列(\D+?)作出最后的图案

string p2 = @".*Lat\D+?(-?[0-9]+\.[0-9]+)\D+Lon\D+?(-?[0-9]+\.[0-9]+)"; 

至于有关解析HTML节点,而不是用正则表达式匹配的评论后,这是通常更好,但在这种情况下,它并没有真正得到你很多的相关元素的内部文本变成是

"\r\nLat: 29.48434, Long: -81.562445 " 

"\r\n\r\n\r\n\r\nCoordinates:\r\nLat: 29.48434, Long: -81.562445 \r\n" 

这两者都需要类似的按摩量来梳理出所需的数据,无论如何,可能与正则表达式无关,除非与剩余内容可预期完全匹配。

+0

非常好的解释。谢谢!现在我知道他们的意思是“贪婪”或“饥饿”或“吞食”! –