【问题标题】:Regex how can I merge execution正则表达式如何合并执行
【发布时间】:2021-03-06 20:01:33
【问题描述】:

我从 .textContent 返回以下缓冲区

            Latitude

    

    32,6549581304256 

    

        Longitude

    

    -16,9288643331225 

我用 dwText = Regex.Replace(dwText, @"\s{2,}", "\n");导致

Latitude
32,6549581304256
Longitude
-16,9288643331225

然后我将这个新输出转换为我的需要 dwText = Regex.Replace(dwText, @"(纬度|经度)(.*)\n", "$1: ");导致

Latitude: 32,6549581304256
Longitude: -16,9288643331225

我的问题是我可以一次性完成这两行吗?

dwText = Regex.Replace( dwText, @"\s{2,}", "\n");
dwText = Regex.Replace( dwText, @"(Latitude|Longitude)(.*)\n", "$1: ");

对于如何更有效地实现这一点,我将不胜感激,谢谢。

【问题讨论】:

  • 您可以尝试正则表达式:(?i)\s*(Latitude)\s*([\d-,.+]+)\s*(Longitude)\s*([\d-,.+]+) 和替换:$1: $2\n$3: $4

标签: c# .net regex replace merge


【解决方案1】:

尝试以下(使用i 标志),

[\S\s]*?([a-z]+)[\S\s]*?([-\d,]+)[\S\s]*?

替换:$1: $2\n

C# Regex Demo


说明

  • [\S\s]*? - 懒惰地匹配 任何东西
  • [a-z]+(第一个捕获组)- 匹配字母单词,不区分大小写。
  • [-\d,]+(第二个捕获组)- 匹配数字、-(连字符)和,(逗号)

【讨论】:

  • 哈哈哈,又快又完美! TYVM 先生。 (我希望我能理解你用正则表达式做了什么)。
  • 与颜色的详细匹配可以是found here,虽然它是PCRE,但对于你的情况来说是一样的。
【解决方案2】:

您可以匹配纬度和经度周围的空白字符并捕获 2 组中的值并在替换中使用这 2 组。

\s*\b(Latitude|Longitude)\s*(-?[0-9]+(?:,[0-9]+)?)\b

说明

  • \s* 匹配 0+ 个空格字符
  • \b(Latitude|Longitude) 一个单词边界,在第 1 组中捕获纬度或经度
  • \s* 匹配 0+ 个空格字符
  • (-?[0-9]+(?:,[0-9]+)?) 捕获组 2,匹配可选的 -,1+ 位可选的小数部分
  • \b一个字边界

替换为:

$1: $2\n

.Net regex demo

【讨论】:

    【解决方案3】:

    为什么不解析出这些值,然后提取它们来做需要的事情呢?

    通过使用名为 captures (?<{NameHere}> ) 的匹配组,可以组织然后提取数据。

    示例 缩短了空格,但它可以跨行并与原始示例一起使用

    var data    = " Latitude  32,6549  Longitude  -16,9288 ";
    var pattern = @"[^\d]+(?<Lat>[\d,]+)[^\d]+(?<Long>[\d,]+)";
    
    var mtch = Regex.Match(data, pattern);
    
    Console.WriteLine($"Latitude: {mtch.Groups["Lat"].Value} Longitude: {mtch.Groups["Long"].Value}");
    
    // Latitude: 32,6549 Longitude: 16,9288
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-30
      • 2018-09-06
      相关资源
      最近更新 更多