3

I'm using the code sample below, and what I want to do is replace all multiple spaces with 1 \t.

So

"I am    having fun             working  on       Regex"

returns

"I am\thaving fun\tworking\ton\tRegex"  

Current code:

RegexOptions options = RegexOptions.None;
Regex regex = new Regex(@"[ ]{2,}", options);     
tempo = regex.Replace(tempo, @" ");

Thanks!

jli
  • 6,523
  • 2
  • 29
  • 37
  • 2
    That's an odd thing to do; tabs are usually expanded to a variable number of spaces, depending on where the tab appears in the line. Incidentally, you should probably edit your question so that it actually asks a question. – Keith Thompson Dec 10 '11 at 23:39
  • and what's the issue then? other than the fact that in your example you only seem to have one space showing up in your string? probably because of space correction issues and that regex.Replace(tempo, @"**"); Should really be regex.Replace(tempo, "\t"); – Ahmed Masud Dec 10 '11 at 23:44

2 Answers2

7

Just do this:

resultString = Regex.Replace(subjectString, " {2,}", @"\t");

you forgot your \t in your try.

FailedDev
  • 26,680
  • 9
  • 53
  • 73
4

In your sample you're replacing multiple spaces with a single one in line:

tempo = regex.Replace(tempo, @" ");

What you want, is to replace with the tab character, which is written \t:

tempo = regex.Replace(tempo, "\t");

Notice that I removed the @ character from the string in the call to Replace, otherwise @"\t" is interpreted as "the string backslash t" instead of the tab character.

madd0
  • 9,053
  • 3
  • 35
  • 62
  • 1
    The answers proposed by FailedDev and madd0 are almost identical but one @-quotes the \t and the other doesn't. Tried both ways. madd0 is correct: Do NOT @-quote the \t. ie `Regex.Replace(subjectString, " {2,}", "\t")` works, `Regex.Replace(subjectString, " {2,}", @"\t")` does not. – Simon Elms Feb 19 '13 at 21:20