1

I'm using Regex.Replace to add a white space after every nth character into a string. I want to give an int variable(number of characters) after which white space should be added but It seems regular expression is not properly written for int variable and hence syntax error arises.

 int num = 8;
    string text="abcdefghijklmnop"
    string result2 = Regex.Replace(text, ".{num}", "$0 "); //not working

this syntax is working

 string result2 = Regex.Replace(text, ".{8}", "$0 ");
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
Emmy
  • 145
  • 11
  • When you say "actual syntax", do you mean that's a working example? It's not clear to me what you mean by "regex.replace() is not accepting int and there is a syntax error" - could you edit your post to clarify that? – Jon Skeet Apr 19 '19 at 07:08
  • 1
    yes. https://stackoverflow.com/questions/9932096/add-separator-to-string-at-every-n-characters – Emmy Apr 19 '19 at 07:09

3 Answers3

3

Regular expressions aren't parameterized in the way that you want, as far as I'm aware. Instead, you need to just build the pattern appropriately.

For most situations in modern C# I'd suggest using an interpolated string literal, which does work in this case, but requires the { and } to be doubled to avoid being treated as format specifiers. It may be more readable to just use string concatenation. So you can either use:

string result = Regex.Replace(text, ".{" + num + "}", "$0 ");

or if you're comfortable with { having different meanings in the same literal:

string result = Regex.Replace(text, $".{{{num}}}", "$0 ");
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

Not sure exactly what you want, but you may build the regex pattern using string concatenation:

int num = Int32.Parse(text_num);
string regex = ".{" + num + "}";
string result2 = Regex.Replace(text, regex, "$0 ");
TextArea1_trim_id.InnerText = result2;

This answer says nothing regarding whether your regex pattern makes any sense or is correct.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

Alternative Linq solution (no regular expressions): we insert " " after each num characters (c)

  int num = 8;
  string text = "abcdefghijklmnop";

  // "abcdefgh ijklmnop " 
  string result2 = string.Concat(text
    .Select((c, i) => (i + 1) % num == 0 
       ? c.ToString() + " " 
       : c.ToString()));

If we don't want to add trailing spaces (and thus we want "abcdefgh ijklmnop")

  string result2 = string.Concat(text
    .Select((c, i) => i < text.Length - 1 && (i + 1) % num == 0 
       ? c.ToString() + " " 
       : c.ToString()));
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215