Alex Art.
Alex Art.

Reputation: 8781

Regex: Replace number of digits in the the middle of a number with special charicters

I have a very large number (it's length may vary) as an input.

And I need a regular expression that will leave first 3 digits and last 3 digits unmodified and will replace all the digits in the between them with some character. The total length of an output should remain the same.

For example:

Input 123456789123456

Output 123xxxxxxxxx456

So far i was able to divide the input number in to 3 the groups by using

^(\d{3})(.*)(\d{3})

The second group is the one that needed to be replaced so it will be something like

$1 {Here goes the replacement of the 2 group} $3

I am struggling with the replacement :

Regex r = new Regex("^(\d{3})(.*)(\d{3})");
r.Replace(input,"$1 {Here goes the replacement of the 2 group} $3")

How should i write the replacement for the 2 group here?

Thanks in advance.

Upvotes: 2

Views: 1198

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174706

You could try the below regex which uses lookbehind and lookahead,

string str = "123456789123456";
string result = Regex.Replace(str, @"(?<=\d{3})\d(?=\d{3})", "x");
Console.WriteLine(result);
Console.ReadLine();

Output:

123xxxxxxxxx456

IDEONE

DEMO

Upvotes: 6

Related Questions