【问题标题】:Use regex to extract a specific value in a string in c#在c#中使用正则表达式提取字符串中的特定值
【发布时间】: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


【解决方案1】:

您可以通过在 {} 中传递 2 个值来定义变量重复,例如\d{1,3} 将匹配 1-3 位数字。

但总的来说,我可能会为此使用较少的正则表达式,因为该格式非常易于解析:

  • 首先,我将所有行作为字符串数组循环。
  • 如果一行为空,则忽略,如果连续两行为空,则创建一个新数据集。
  • 如果该行包含:,则在此处拆分该行:左侧部分成为键,右侧部分成为值。
  • 如果该行不包含 :,则它要么被忽略,要么引发错误标志(或引发异常等)。
  • 然后您可以使用简单的字符串匹配(比正则表达式更快)来确定“键”的含义。
  • 另一个正则表达式(或类似Double.Parse())然后从右侧提取值。请记住,这些转换函数只会跳过无效字符并丢弃它们后面的任何内容。
  • 然后可以使用简单的正则表达式解析更复杂的条目(如坐标或时间戳;或单位很重要的条目)。

简化代码(不一定 100% 可编译/正确):

String[] lines = fileContents.Split({'\n'}); // split the content into separate lines

bool wasEmpty = false;
foreach (String line in lines) {
    line = line.Trim(); // remove leading/trailing whitespaces
    if (line.Length == 0) { // line is empty
        if (wasEmpty) { // last line was empty, too
            // init a new dataset
        }
        else
            wasEmpty = true;
        continue; // skip to next entry
    }
    wasEmpty = false;
    String content = line.split({':'}); // split the line into a key/value pair
    if (content.Length != 2) // not exactly two entries
        continue; // skip
    // content[0] now has the "key" (like "Lat/Long")
    // content[1] now has the "value" (like "18.38891, -66.12175")
    // both can be evaluated using regular expressions
}

【讨论】:

  • 昨晚我在这工作,但没有以 100% 的速度工作。当 i = 0 在第一个 if 中输入时,操作正常。然后它应该去其他 else if,比较什么都不做,然后增加 i 并再次评估,这一次它假设进入第一个 else if 但没有进入。有什么建议吗??
  • for(int i=0;i c != "." && c.Trim() != ""); x= double.Parse(num.ElementAt(0)); i = i + 1;} else if (distance[i]=="Direccion en grados") {var num = Regex.Split(distance.ElementAt(i+1), @"[^0-9\.\- ]+").Where(c => c != "." && c.Trim()!=""); z = double.Parse(num.ElementAt(0)); }else if (distance[i] == "Persona encontrada en") {var num = Regex.Split(distance.ElementAt(i+1), @"[^0-9\.\-]+").Where (c => c != "." && c.Trim() != ""); latlong = num.ElementAt(0); } }
  • 评论对此类事情不利,如果相关,您应该将其添加到您的初始问题中,否则创建一个新问题。
【解决方案2】:

在您的正则表达式中,第二部分的名称是degress。在代码中,您使用的是degree

在您的正则表达式中,第二部分的名称是latlong。在代码中,您使用的是Lat/Long

因此,不,您将无法获得这两个组。

【讨论】:

  • 我从西班牙语翻译成英语时出现拼写错误。在代码中是正确的。
猜你喜欢
  • 2021-05-24
  • 1970-01-01
  • 1970-01-01
  • 2017-11-18
  • 1970-01-01
  • 2019-03-13
  • 1970-01-01
  • 2020-04-10
  • 1970-01-01
相关资源
最近更新 更多