Regex for matching over 2 lines

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • svendok
    New Member
    • Jun 2010
    • 25

    Regex for matching over 2 lines

    Hi,
    I have thousands of lines of code like this:
    Code:
    Blah1 blah1 blah1 = A1;
    Yada1 yada1 yada1 = B1;
    Blah2 blah2 blah2 = A2;
    Yada2 yada2 yada2 = B2;
    I want to swap the A value with the B value.

    What is the syntax for a Perl regex that would do this? I'm struggling with the line break.

    Thanks in advance.

    svend
  • Rabbit
    Recognized Expert MVP
    • Jan 2007
    • 12517

    #2
    Assuming you have multi-line turned on, \r\n represents a line break in windows while \n represents a line break in unix.

    Comment

    • svendok
      New Member
      • Jun 2010
      • 25

      #3
      Thank you! I can't believe I forgot that...

      So I guess the patterns would be:
      Search:
      Code:
      (.*) = (.*)\r\n(.*) = (.*)
      Replace:
      Code:
      $1 = $4\r\n$3 = $2
      Last edited by svendok; Feb 25 '11, 05:18 PM. Reason: Giving code.

      Comment

      • Rabbit
        Recognized Expert MVP
        • Jan 2007
        • 12517

        #4
        If you have trouble with the "." you may want to try ([^\r\n]*)

        Comment

        • miller
          Recognized Expert Top Contributor
          • Oct 2006
          • 1086

          #5
          perl automatically treats \n as \r\n internally on windows machines, so it is unnecessary to do that. At most, you might need to do \r?\n if you're working with files cross platform, but I wouldn't expect that you are.

          Anyway, here's a script that switches the values of every odd and even line:

          Code:
          use strict;
          
          my $data = do {local $/; <DATA>};
          
          $data =~ s{(.*?) = (.*?)\n(.*?) = (.*?)\n}{$1 = $4\n$3 = $2\n}g;
          
          print $data;
          
          __DATA__
          Blah1 blah1 blah1 = A1;
          Yada1 yada1 yada1 = B1;
          Blah2 blah2 blah2 = A2;
          Yada2 yada2 yada2 = B2;
          Blah3 blah3 blah3 = A3;
          Yada3 yada3 yada3 = B3;

          Comment

          • svendok
            New Member
            • Jun 2010
            • 25

            #6
            Thanks, Miller, that's very helpful! Didn't know that about Perl and Windows line breaks.

            Comment

            Working...