Regex & \n

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Svinja
    New Member
    • Nov 2007
    • 25

    Regex & \n

    Hi,
    I want to replace "\n" with "!" in c#, i tried this:
    Code:
    String buffer=richTextBox.Text;
    buffer=buffer.Replace(@"\n", "!");
    and it worked, but this didnt:
    Code:
     
    String buffer=richTextBox.Text;
    buffer = Regex.Replace(buffer, @"\n", "!");
    why?
  • balame2004
    New Member
    • Mar 2008
    • 142

    #2
    Originally posted by Svinja
    Hi,
    I want to replace "\n" with "!" in c#, i tried this:
    Code:
    String buffer=richTextBox.Text;
    buffer=buffer.Replace(@"\n", "!");
    and it worked, but this didnt:
    Code:
     
    String buffer=richTextBox.Text;
    buffer = Regex.Replace(buffer, @"\n", "!");
    why?
    Hi,

    Regex.Replace is working fine for me. Let me know with full source code so i can able to find out the issue.

    Regards,
    Balaji U

    Comment

    • Svinja
      New Member
      • Nov 2007
      • 25

      #3
      Code:
      String buffer=richTextBox.Text;
      buffer = Regex.Replace(buffer, @"\n", "!");
      //buffer=buffer.Replace(@"\n", "!");
      MessageBox.Show(buffer);
      there it is mate, as you can see i am geting text from richtextbox but if i put the text in the string manually like this:
      Code:
      buffer = Regex.Replace("a\nb", @"\n", "!");
      then it works. I guess it has something to do with the fact that \n is single char and regex works only with strings, i really dont understand this.

      Comment

      • Svinja
        New Member
        • Nov 2007
        • 25

        #4
        ok i figured it out, once again, the solution was hiding in the MSDN. It turns out that "\" is a special char for regex.replace so i cant use it. If i want to match "\" i must use "\\" like this:
        Code:
        String buffer=richTextBox.Text;
        buffer = Regex.Replace(buffer, @"\\n", "!");
        MessageBox.Show(buffer);
        but anyway thx for answering.

        Comment

        Working...