【发布时间】:2013-05-05 20:10:44
【问题描述】:
我正在通过串行端口通信以字符串形式接收我的数据。那部分工作正常。数据格式如下:
Distance run: 36in.
Direction in degrees: 275
Total of person founds:11
New Person found in:
Lat/Long: 18.38891, -66.12174
Date: 5/4/2013 Time: 19:13:35.0
Total of person founds:12
New Person found in:
Lat/Long: 18.38891, -66.12175
Date: 5/4/2013 Time: 19:13:37.0
Distance run: 15in.
Direction in degrees: 215
Total of person founds:13
New Person found in:
Lat/Long: 18.38891, -66.12174
Date: 5/4/2013 Time: 19:13:39.0
Distance run: 30in.
Direction in degrees: 180
但这可能会有所不同,因为在每个人创建的博客之间(包括它在纬度/经度、日期和时间中的位置)可能会有另一个距离和方向(以度为单位)。
我尝试过正则表达式,但不确定如何很好地使用它。我什至有一个只提取数字的正则表达式。
var xnumbers = Regex.Split(strFileName, @"[^0-9\.\-]+").Where(c => c != "." && c.Trim() != "");
我想要的是提取距离跑的具体值:第一个值是 36in 并存储它等等。然后获取以度为单位的方向值并将其存储在另一个变量中,最后获取 lat & long 并将其存储在另一个变量中。我需要这些值来创建一个列表,以便以后使用该数据并绘制它。我已经有了绘图部分。
我试过了:
我知道这种模式只考虑到距离仅为 2 个数字,但该值可以是 1 或 3 个数字(例如:距离跑:1 英寸或距离跑:219 英寸)
string pattern = @"^Distance Run:(?<distance>.{2}),Direction in degrees:,(?<degress>. {3}),Lat/Long:(\+|\-)(?<latlong>.{18})$";
string distance = string.Empty;
string degrees = string.Empty;
string latlong = string.Empty;
Regex regex = new Regex(pattern);
if (regex.IsMatch(strFileName)) // strFileName is the string with the data
{
Match match = regex.Match(strFileName);
foreach (Capture capture in match.Groups["distance"].Captures)
distance = capture.Value;
foreach (Capture capture in match.Groups["degree"].Captures)
degrees = capture.Value;
foreach (Capture capture in match.Groups["Lat/Long"].Captures)
latlong = capture.Value;
}
但是不工作。我会感谢任何帮助和建议。提前致谢。
【问题讨论】:
-
我相信您正在超越正则表达式的随意使用。您是否考虑过使用自己的解析器?语法足够简单,简单解析是每个开发者工具包中应该具备的技能。
-
你能给出一个示例代码来做这些操作吗?提前致谢。
-
向费马道歉:我找到了一种非常优雅的方式来向您展示它;不幸的是,这条评论的边距太小,无法包含它。
-
可以通过电子邮件发送吗?
-
否;我不是您的个人代码编写服务。我的最后一条评论是个玩笑,如果您没有明白,我深表歉意。 (如果你有兴趣,谷歌
Fermat's Last Theorem。)我提交了一条评论,试图引导你走向一个有用的方向。随心所欲地去做。网络上有大量的开源解析工具和教程。
标签: c# regex string data-extraction