1

What is the RegEx to put whitespace per 4 characters

For example I have an IBAN number like this

BE45898287271283

I want to format it like this

BE45 8982 8727 1283

Any help is appreciated.

Tassisto
  • 9,235
  • 27
  • 93
  • 145

4 Answers4

9

You can try this

string test = "BE45898287271283";
test = Regex.Replace(test, ".{4}", "$0 ").Trim();
Sachin
  • 39,043
  • 7
  • 86
  • 102
1

Using a RegEx;

foo = Regex.Replace(foo, ".{4}", "$0 ");
Alex K.
  • 165,803
  • 30
  • 257
  • 277
1
private string Group4(string s)
{
    string output="";
    for(int i=0; i < s.Length; i+=4)
        output+=s.Substring(i, 4) + ' ';

    return s.TrimEnd();
}
dotNET
  • 31,005
  • 20
  • 138
  • 226
0

Try this regex instead:

[a-z\d]{4}

string in="BE45898287271283";
string out = Regex.Replace("(?i)([a-z\\d]{4})", "$1 ");
Stephan
  • 40,082
  • 60
  • 228
  • 319