【问题标题】:Select the last number via regex when identifying (string + number)识别时通过正则表达式选择最后一个数字(字符串+数字)
【发布时间】:2020-11-22 19:17:13
【问题描述】:

我有以下几句话:

Say.2 Sing"3 Final5 Note:10 Music99 Sing1

我需要你用(string + number) 看起来像这样:

我试过这样:

[^\s\d]\d+

但总是在前面出现一个字符串而不是数字:

我通过 C# 中的代码将最后这些数字替换为 \n。我只需要一个有效的正则表达式。

private void method()
{
    string text = "Say.2 Sing"3 Final5 Note:10 Music99 Sing1";
    string ntext = Regex.Replace(text, @"[^\s\d]\d+", "\n");
    Console.WriteLine(ntext);
}

但在输出中是这样的:

Say
Sing
Fina
Note
Musi
Sin

我需要你看起来像这样:

Say.    
Sing"    
Final    
Note:    
Music
Sing

【问题讨论】:

  • 为什么不只是\d+
  • 这是因为我有一个文本,并且在该文本中有一些带有模式的单词(字符串 + 数字),我需要删除末尾的数字
  • \d+ 将完美匹配您所有的黄色标记。你试过了吗?
  • 我需要在数字前有一个字符串,所以选择那个数字
  • 然后使用正向后视结构:(?<=[^\s\d])\d+。当前面有除空格或数字之外的任何内容时,这将匹配一系列数字。

标签: c# .net regex


【解决方案1】:

使用

using System;
using System.Text.RegularExpressions;
 
public class Test
{
    public static void Main()
    {
        var text = "Say.2 Sing\"3 Final5 Note:10 Music99 Sing1";
        var result = Regex.Replace(text, @"(?<![\s0-9])[0-9]+\s*", "\n");
        Console.Write(result);
    }
}

proof

说明

--------------------------------------------------------------------------------
  (?<!                     look behind to see if there is not:
--------------------------------------------------------------------------------
    [\s0-9]                  any character of: whitespace (\n, \r,
                             \t, \f, and " "), '0' to '9'
--------------------------------------------------------------------------------
  )                        end of look-behind
--------------------------------------------------------------------------------
  [0-9]+                   any character of: '0' to '9' (1 or more
                           times (matching the most amount possible))
--------------------------------------------------------------------------------
  \s*                      whitespace (\n, \r, \t, \f, and " ") (0 or
                           more times (matching the most amount
                           possible))

【讨论】:

    【解决方案2】:

    您还可以使用捕获组捕获您想要保留的内容,并匹配您想要删除的内容。

    在替换使用组 1 和换行符。

    ([^\d\s]+)\d+\s*
    
    • ([^\d\s]+) 捕获组 1,匹配 1+ 个字符而不是数字或空白字符
    • \d+ 匹配 1+ 位(或使用 [0-9] 匹配 0-9 位)
    • \s* 匹配 0+ 个空格字符

    .NET Regex demo | C# demo

    string text = "Say.2 Sing\"3 Final5 Note:10 Music99 Sing1";
    string ntext = Regex.Replace(text, @"([^\d\s]+)\d+\s*", "$1\n");
    Console.WriteLine(ntext);
    

    输出

    Say.
    Sing"
    Final
    Note:
    Music
    Sing
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-31
      • 1970-01-01
      • 1970-01-01
      • 2016-11-13
      • 1970-01-01
      • 1970-01-01
      • 2021-05-16
      • 1970-01-01
      相关资源
      最近更新 更多