12

I have a pipe delimited string of NAME|VALUE pairs looking something like this..

Name1|Value1|Name2|Value2|Name3|Value3

What I want to do is to replace every second instance of | with a new line so that I have something like this..

Name1|Value1
Name2|Value2
Name3|Value3

My issue isn't the new-line, as I know I can use \r\n for that, but rather the regex part that only replaces every second instance of |.

3 Answers3

12

Find: ([^\|]*\|[^\|]*)\|
Replace to: \1\n

nixda
  • 27,634
5

I want to replace every second instance of | with a new line

  • Menu "Search" > "Replace" (or Ctrl + H)

  • Set "Find what" to (.*?\|.*?)[\|]

  • Set "Replace with" to \1\r\n

  • Enable "Regular expression"

  • Click "Replace All"

    enter image description here

Before:

Name1|Value1|Name2|Value2|Name3|Value3

After:

Name1|Value1
Name2|Value2
Name3|Value3

Notes:

  • The above assumes you are editing a text file with Windows EOLs, \r\n.

  • If you are using files with different EOLs you can convert them to Windows EOLs using Menu "Edit" > "EOL Conversion".

  • If you aren't working with Windows EOL, and you don't wish to convert them, use the following instead:

    • Use \n instead of \r\n for Unix/OS X EOLs

    • Use \r instead of \r\n for Mac OS (up to version 9) EOLs


Further reading

DavidPostill
  • 162,382
0

This attempts to show how to replace every Nth character with a newline without copy-pasting parts of the sequence. In such case a number is needed to tell the engine how many repetitions are expected. In this example I want to replace every 13th occurrence of character @ with a newline. You can see 12 (13-1) repetitions of non-capturing group plus remaining text before the 13th character @ in one captured group. Then there's matched, but not captured 13th character @ which will be replaced with \r\n.

Find what: ((?:.*?\@){12}.*?)\@
Replace with: $1\r\n
Check Wrap around
Search Mode = Regular expression
Replace All

The character @ should be changed to your actual separator character (it's repeated two times in the pattern). E.g., if your separator is |, your pattern would be ((?:.*?\|){12}.*?)\|
Also, the number 12 should be replaced with your value (N-1).

ZygD
  • 2,577