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!

2
  • 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. Commented Dec 10, 2011 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, @"<tab>"); Should really be regex.Replace(tempo, "\t"); Commented Dec 10, 2011 at 23:44

2 Answers 2

7

Just do this:

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

you forgot your \t in your try.

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.