【问题标题】:C# Regex Replace sequence of numbers preceded with a spaceC#正则表达式替换前面有空格的数字序列
【发布时间】:2022-01-15 21:15:02
【问题描述】:

我有这个字符串:

Hello22, I'm 19 years old

如果前面有空格,我只想用 * 替换数字,所以它看起来像这样:

Hello22, I'm ** years old

我一直在尝试一堆正则表达式,但没有运气。希望有人可以帮助使用正确的正则表达式。谢谢。

我尝试过的正则表达式:

Regex.Replace(input, @"([\d-])", "*");

返回所有替换为 * 的数字

Regex.Replace(input, @"(\x20[\d-])", "*");

没有按预期工作

【问题讨论】:

  • 请在问题中包含您尝试过的一些正则表达式。
  • (?<= )[0-9]+ 或者,可能是\b[0-9]+\b(这里\b 是一个分词,这就是为什么所有19 都会匹配19, as I say, 19, I'm 19
  • 德米特里有正确的答案。谢谢
  • @Alberto 如果 Dmitry 有正确答案,您应该将其标记为已接受。
  • 这能回答你的问题吗? Reference - What does this regex mean?

标签: c# regex


【解决方案1】:

在 C# 中,您还可以使用带有后视和无限量词的模式。

(?<= [0-9]*)[0-9]

模式匹配:

  • (?&lt;= 正向向后看,断言当前位置左边是什么
    • [0-9]* 匹配空格后跟可选数字 0-9
  • ) 近距离观察
  • [0-9]\匹配单个数字0-9

例子

string s = "Hello22, I'm 19 years old";
string result = Regex.Replace(s, "(?<= [0-9]*)[0-9]", "*");
Console.WriteLine(result);

输出

Hello22, I'm ** years old

【讨论】:

    【解决方案2】:

    你可以试试(?&lt;= )[0-9]+模式在哪里

    (?<= ) - look behind for a space
    [0-9]+ - one or more digits.
    

    代码:

    string source = "Hello22, I'm 19 years old";
    
    string result = Regex.Replace(
      source, 
     "(?<= )[0-9]+", 
      m => new string('*', m.Value.Length));
    

    看看\b[0-9]+\b(这里\b代表word bound)。这种模式 将替换"19, as I say, 19, I'm 19" 中的所有19(注意,第一个19 前面没有空格):

    string source = "19, as I say, 19, I'm 19";
    
    string result = Regex.Replace(
       source, 
     @"\b[0-9]+\b", 
       m => new string('*', m.Value.Length)); 
    

    【讨论】:

      猜你喜欢
      • 2013-03-09
      • 1970-01-01
      • 2020-09-12
      • 1970-01-01
      • 2021-07-04
      • 1970-01-01
      • 1970-01-01
      • 2015-05-10
      • 2021-04-24
      相关资源
      最近更新 更多