Home > Blockchain >  Insert a space into a string from right to left every 4 characters
Insert a space into a string from right to left every 4 characters

Time:04-05

Input: 121234123412341234
Expected result: 12 1234 1234 1234 1234

Tried with:

Regex.Replace(input, @".{4}", "$0 ", RegexOptions.RightToLeft);

...which produces "121234 1234 1234 1234 " (with a space at the end)

So, the goal is to split into 4 (or less) chars groups starting from the end.

CodePudding user response:

If the input is actually a number, you can use number formatting to do this:

const long num = 121234123412341234;

var nfi = new NumberFormatInfo
{
    NumberGroupSeparator = " ",
    NumberGroupSizes = new[] { 4 }
};

var result = num.ToString("#,#", nfi);

And result is 12 1234 1234 1234 1234

CodePudding user response:

Try @"(?=(?:.{4}) $)"; you don't even need to go right-to-left. It simply finds each place in the string where the number of remaining characters is divisible by four (but not zero).

This regexp finds zero-width matches, so simply replace with " ".

EDIT: If you need to also ensure you don't get a match at the start of a string that has length divisible by 4, you can use an extra assertion: @"(?<=.)(?=(?:.{4}) $)".

NOTE: If it is about numeral formatting, in real circumstances you should absolutely use Charles Mager's answer instead. This is answering the literal question as tagged - how to do this with regular expressions.

  • Related