0

I am trying to replace numbers in a string with the "N" character. What I've done and works properly is:

    string str = "abc1234def";          
    str = Regex.Replace(g, @"\d+", "N");`

the output of the above will give "abcNdef" since the "1234" will be replaced with "N". The aim now is to replace with "N" every single number so for the above input, the output would be "abcNNNNdef".

Any help would be welcome

Erresen
  • 1,923
  • 1
  • 22
  • 41
George George
  • 571
  • 3
  • 7
  • 18
  • 2
    Remove the `+` quantifier. Haven't tested it, but makes sense as it wouldn't consider `1234` as a single match. – Broots Waymb Feb 13 '19 at 21:43
  • 1
    Do you have a requirement to use RegEx? Otherwise you write simple loop over string and replace every `.IsDigit()` char with N. – Samvel Petrosov Feb 13 '19 at 21:49
  • 1
    Is the first variable supposed to be `g` rather than `str`? You don't show `g` declared anywhere, but based on your expected output, that seems to be the case. – Broots Waymb Feb 13 '19 at 21:50

2 Answers2

2

Just remove the + quantifier. Then each digit is considered separately, rather than as 1234 being a single match to replace.

str = Regex.Replace(g, @"\d", "N");  

This is assuming that g is "abc1234def" and results in "abcNNNNdef" for str.

You can read more about the quantifiers in the docs here.

Broots Waymb
  • 4,713
  • 3
  • 28
  • 51
1

Try this

string replacedText = Regex.Replace("abc1234def", @"([0-9]{1})", "N");

regular expression "([0-9]{1})" will match every single number separately and then Replace function will replace each match with N

Johnny
  • 8,939
  • 2
  • 28
  • 33