Home > Software design >  C# Regex Replace sequence of numbers preceded with a space
C# Regex Replace sequence of numbers preceded with a space

Time:12-12

I have this string:

Hello22, I'm 19 years old

I just want to replace the number with * if its preceded with a space, so it would look like this:

Hello22, I'm ** years old

I've been trying a bunch of regexes but no luck. Hope someone can help out with the correct regex. Thank you.

Regexes which I tried:

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

Returns all numbers replaced with *

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

Does not work as expected

CodePudding user response:

You can try (?<= )[0-9] pattern where

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

Code:

string source = "Hello22, I'm 19 years old";

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

Have a look at \b[0-9] \b (here \b stands for word bound). This pattern will substitute all 19 in the "19, as I say, 19, I'm 19" (note, that 1st 19 doesn't have space before it):

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)); 

CodePudding user response:

In C# you could also make use of a pattern with a lookbehind and an infinite quantifier.

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

The pattern matches:

  • (?<= Positive lookbehind, assert what is to the left of the current position is
    • [0-9]* Match a space followed by optional digits 0-9
  • ) Close lookbehind
  • [0-9]\ Match a single digit 0-9

Example

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

Output

Hello22, I'm ** years old
  • Related