Akawan
Akawan

Reputation: 103

Add separator to string with regex in C#

Suppose the string is:

string x = "0000000000";

I want to add a seperator like "." after each 3 character group starting from the end.

Output should be :

0.000.000.000

How could I do this?

Upvotes: 0

Views: 302

Answers (3)

Soner Gönül
Soner Gönül

Reputation: 98750

As a non-regex solution, you can use Batch from MoreLINQ to get equally sized strings and reverse it and combine with string.Join like;

string s = "0000000000";
var group = s.Batch(3, p => new string(p.ToArray())).ToList();
group.Reverse();
var result = string.Join(".", group);
Console.WriteLine(result); // 0.000.000.000

Upvotes: 1

vks
vks

Reputation: 67968

(?=(?:\d{3})+$)

You can simply use this and replace by ..See demo.

https://regex101.com/r/vH0iN5/13

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626802

You need to use the following regex:

(\d)(?=(?:\d{3})+(?!\d))

And replace with $1.

Here is a RegexStorm demo (see Context tab on that page)

var rx = new Regex(@"(\d)(?=(?:\d{3})+(?!\d))");
var res = rx.Replace("0000000000", "$1.");

Upvotes: 1

Related Questions