Sara Hamad
Sara Hamad

Reputation: 785

How to combine lines in regular expressions?

So i am new to regular expressions and i am learning them using a simple text editor only. I have the following file

          84544484N
          32343545M
          32334546E
          34456434M

I am trying to combine each pair of lines into one tab delimited line The result should be :

        84544484N  32343545M
        32334546E  34456434M

I wrote the following :

            Search: (.*?)\n(.*?)
            Replace: \1\t\2

this did not work can someone please explain why and give me the correct solution. Thank you!!

Upvotes: 5

Views: 6372

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626690

The (.*?)\n(.*?) pattern will never work well because the (.*?) at the end of the pattern will always return an empty string (since *? is a lazy matching quantifier and if it can return zero characters (and it can) it will. Use greedy matching and adjust the pattern like:

(.+)\r?\n *(.*)

or - since SublimeText uses Boost regex - you can match any newline sequence with \R:

(.+)\R *(.*)

and replace with \1\t\2. Note I replaced *? with + in the first capturing group because you need to match non-empty lines.

Regex breakdown:

  • (.+) - one or more characters other than a newline (as many as possible) up to
  • \R - a newline sequence (\r\n, \r or just \n)
  • * - a literal space, zero or more occurrences
  • (.*) - Group 2: zero or more characters other than a newline (as many as possible)

enter image description here                                                                      / enter image description here

Upvotes: 3

Related Questions